[Haskell] Stack

1. 列表表示

module Stack(Stack,push,pop,top,emptyStack,stackEmpty) where

newtype Stack a  = Stk [a]

push :: a -> Stack a -> Stack a
push x (Stk xs) = Stk (x:xs)

pop :: Stack a -> Stack a 
pop (Stk []) = error "pop from an empty stack"
pop (Stk (_:xs)) = Stk xs

top :: Stack a -> a 
top (Stk []) = error "top from an empty stack"
top (Stk (x:_)) = x 

emptyStack :: Stack a
emptyStack = Stk [] 

stackEmpty :: Stack a -> Bool
stackEmpty (Stk []) = True
stackEmpty (Stk _) = False

2. 自定义类型表示

module Stack(Stack,push,pop,top,emptyStack,stackEmpty) where

data Stack a  = EmptyStack | Stk a (Stack a)

push :: a -> Stack a -> Stack a
push x s = Stk x s

pop :: Stack a -> Stack a 
pop EmptyStack = error "pop from an empty stack"
pop (Stk _ s) = s

top :: Stack a -> a 
top EmptyStack = error "top from an empty stack"
top (Stk x _) = x 

emptyStack :: Stack a
emptyStack = EmptyStack

stackEmpty :: Stack a -> Bool
stackEmpty EmptyStack = True
stackEmpty _ = False

参考

Algorithms: A Functional Programming Approach

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容