【问题标题】:Writing pop and push functions for Haskell stack为 Haskell 堆栈编写 pop 和 push 函数
【发布时间】: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 Emptypush x mystack = Elem x mystack吗? (另外,这两个方程中的第一个是多余的)

标签: haskell stack


【解决方案1】:

提示:以下是使用内置列表实现堆栈操作的方法:

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 xsx:xs 的另一种写法。

要自己输入MyStack,请注意您的Empty 实际上就像[] 一样工作,而Elem 等效于(:)。我不会直接给你代码来做这件事,因为自己弄清楚是一半的乐趣!

【讨论】:

  • 如果你使用(:)而不是中缀:来表明:只是一个数据构造函数,与Elem一样,这种关系可能会更明显一些,甚至虽然语法有点不同。
  • 谢谢你,你的提示真的很有帮助。我终于想通了:)
  • 当我写这样的函数时:push :: Char -> Stack ->Stack push x Empty = (Element x Empty) push x stack = (Element x stack) 我得到这个输入的错误:push 'a' Element 'b' Empty我得到这个输出Element 'a' (Element 'b' Empty)这个输入push 'a' (Element 'b' Empty)我怎样才能得到这个输出:@ 987654337@ 此输入:push 'a' Element 'b' Empty 再次感谢您的帮助。
  • 您的函数运行正常。 push 的第二个参数需要括号括起来。 Haskell 的语法就是这样设计的。
猜你喜欢
  • 2010-09-30
  • 2013-04-20
  • 2016-08-16
  • 1970-01-01
  • 2011-05-04
  • 2016-10-24
  • 1970-01-01
  • 2013-12-21
  • 1970-01-01
相关资源
最近更新 更多