【发布时间】:2023-04-01 02:55:01
【问题描述】:
您好,我正在尝试为这样定义的 Haskell 堆栈创建 pop 和 push 函数:
data mystack = Empty | Elem Char mystack deriving Show
如果我没有这个定义限制,我会像这样推送
push x mystack = (x:mystack)
然后像这样弹出
pop mystack = head mystack
但是有了这个限制,我不知道如何实现这些功能。 你能给我一些提示吗? 我什至无法自己编写带有该描述的 Stack 类型。
【问题讨论】:
-
你绝对需要阅读this
-
您还需要检查您的标识符。
data关键字后面的标记应以大写字母开头:data MyStack = Empty | Elem Char MyStack deriving (Show) -
ps,您可能没有意识到,但实际上您只是重新定义了内置列表。
MyStack与[Char]相同(与String相同),只是具有不同名称的值构造函数。 -
现在我可以编写像 Elem 'a' Elem 'b' Empty 这样的堆栈了。我试着写这样的推送功能:
push x Empty = Element xpush x MyStack = Element x MyStack它没有用。 -
不应该是
push x Empty = Elem x Empty和push x mystack = Elem x mystack吗? (另外,这两个方程中的第一个是多余的)