您好我正在尝试为定义如下的 Haskell 堆栈创建 pop 和 push 函数:
data mystack = Empty | Elem Char mystack deriving Show
如果我没有这个定义限制,我会像这样插入
push x mystack = (x:mystack)
像这样流行
pop mystack = head mystack
但是有了这个限制,我不知道如何实现这些功能。
你能给我一些提示吗?
我什至无法自己编写带有该描述的 Stack 类型。
最佳答案
提示:这是使用内置列表实现堆栈操作的方法:
push :: a -> [a] -> ((),[a]) -- return a tuple containing a 'nothing' and a new stack
push elem stack = ((), (:) elem stack)
pop :: [a] -> (a, [a]) -- return a tuple containing the popped element and the new stack
pop [] = error "Can't pop from an empty stack!"
pop ((:) x stack) = (x, stack)
(:) x xs
是另一种写作方式x:xs
.自己做
MyStack
键入,请注意您的 Empty
实际上就像 []
, 和 Elem
相当于(:)
.我不会直接给你代码来做这件事,因为自己弄清楚是一半的乐趣!
关于haskell - 为 Haskell 堆栈编写 pop 和 push 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15175543/