我是函数式编程的新手,我正在尝试用 Haskell 创建和展示一个 Stack。我希望我的程序向我展示我正在使用它构建的堆栈。这是我的代码:
module Stack (Stack, empty, push, pop, top, isEmpty) where
data Stack a = EmptyStack | Stk a (Stack a)
push x s = Stk x s
top (Stk x s) = x
pop (Stk _ s) = s
empty = EmptyStack
isEmpty EmptyStack = True
isEmpty (Stk x s) = False`
instance Show a => Show (Stack a) where
show EmptyStack = "|"
show (Stk a b) = (show a) ++ " <- " ++ (show b)
使用“show (push 1 empty)”,我希望得到一个答案(或多或少):“1 <- |”但我无法编译代码。当我尝试时,它显示以下错误:
[1 of 1] Compiling Stack ( Stack.hs, interpreted )
Stack.hs:12:27:
Ambiguous occurrence ‘show’
It could refer to either ‘Stack.show’, defined at Stack.hs:11:9
or ‘Prelude.show’,
imported from ‘Prelude’ at Stack.hs:1:8-12
(and originally defined in ‘GHC.Show’)
Stack.hs:12:47:
Ambiguous occurrence ‘show’
It could refer to either ‘Stack.show’, defined at Stack.hs:11:9
or ‘Prelude.show’,
imported from ‘Prelude’ at Stack.hs:1:8-12
(and originally defined in ‘GHC.Show’)
Failed, modules loaded: none.
我理解程序可能会将 Prelude 中的“表演”与 be 定义的“表演”混淆的错误,但我在代码中看不到该错误。此外,有些伙伴的代码相同,程序运行良好。
有什么我必须改变或我错过了?
谢谢!