我需要在 haskell 中创建堆栈数据类型才能像这样编写:
let a = emptyStack
push 10 a
//[10]
pop a
[]
Run Code Online (Sandbox Code Playgroud)
我想要推送看起来像
push :: a -> Stack a -> Stack a
push a b = a:b
Run Code Online (Sandbox Code Playgroud)
但我在语法上有问题,到底如何声明这个新的数据类型,所以
let a = emptyStack
:t a
Run Code Online (Sandbox Code Playgroud)
会显示堆栈
有关语法的任何提示
你可以写
import Data.Maybe
data Stack a = Stack [a] deriving Show
empty :: Stack a
empty = Stack []
push :: a -> Stack a -> Stack a
push x (Stack xs)= Stack (x:xs)
pop :: Stack a -> (Maybe a, Stack a)
pop (Stack []) = (Nothing, Stack [])
pop (Stack (x:xs)) = (Just x, Stack xs)
Run Code Online (Sandbox Code Playgroud)
例子
*Main> push 4 $ push 3 empty
Stack [4,3]
*Main> pop $ push 4 $ push 3 empty
(Just 4,Stack [3])
Run Code Online (Sandbox Code Playgroud)
这种方法是严格检查类型参数(与 @mhwombat 解决方案相反)。一种或另一种方法是有效的(在某些情况下一种方法比另一种方法更好,反之亦然)。