haskell - 为 Haskell 堆栈编写 pop 和 push 函数

标签 haskell stack

您好我正在尝试为定义如下的 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/

相关文章:

haskell - Haskell 中的子字符串替换问题

haskell - 如何安全地 `mapM` 超过 `System.IO.openFile`

Haskell 可扩展 IO 异常?

stack - OCaml 元组栈

haskell - Haskell 中的约束、函数组合和 let 抽象

haskell - 如何避免 "‘main’ 未在模块 ‘Main’ 中定义“使用合成时

java - 创建一个 "calculator"来评估 Java 中的算术表达式 - 代码问题

C 堆栈指向地址?

在c程序的运行中更改堆栈

c - 将链表中的值插入到堆栈中