Haskell 实例展示-can';我无法编译它

Haskell 实例展示-can';我无法编译它,haskell,Haskell,我在大学里遇到了这样的问题: data Expression a = Constant a | Simetric (Expression a) | Addition (Expression a) (Expression a) | Subtraction (Expression a) (Expression a) | Multiplication (Express

我在大学里遇到了这样的问题:

data Expression a = Constant a 
                | Simetric (Expression a) 
                | Addition (Expression a) (Expression a) 
                | Subtraction (Expression a) (Expression a) 
                | Multiplication (Expression a) (Expression a)
我必须写一个表达式作为Show的一个例子

这是我的密码:

instance Show Expression where
               show (Constant x) = (show x)
               show (Simetric x) = "-" ++ (show x)
               show (Addition x y) = (show x) ++ " + " ++ (show y)
               show (Subtraction x y) = (show x) ++ " - " ++ (show y)
               show (Multiplication x y) = (show x) ++ " * " ++ (show y)
当我尝试编译时,我在ghci上收到以下错误消息:

    Expecting one more argument to ‘Expression’
The first argument of ‘Show’ should have kind ‘*’,
  but ‘Expression’ has kind ‘* -> *’
In the instance declaration for ‘Show Expression’
Failed, modules loaded: none.

有人能解释一下我的代码出了什么问题吗?我星期一有期末考试。谢谢你的帮助

您应该阅读编译器的消息,因为它尽力提供帮助

Expecting one more argument to ‘Expression’
让我们添加一些论点

instance Show (Expression a) where
GHC再次抱怨:

No instance for (Show a) arising from a use of ‘show’
Possible fix:
  add (Show a) to the context of the instance declaration
好的,让我们在上下文中添加
Show a

instance Show a => Show (Expression a) where
现在它编译得很好。顺便说一下,您不需要在
show
周围使用大括号:

instance Show a => Show (Expression a) where
    show (Constant x) = show x
    show (Simetric x) = "-" ++ show x
    show (Addition x y) = show x ++ " + " ++ show y
    show (Subtraction x y) = show x ++ " - " ++ show y
    show (Multiplication x y) = show x ++ " * " ++ show y

如果有多个类约束,您需要大括号,仅供参考。非常感谢!这完美地解决了我的问题!但是我不明白为什么我必须在您执行的第4步中将Show a添加到上下文中。要在实例定义中使用
Show x
,您需要
x
才能显示。不能显示非
show
实例的内容。例如,
常量id
,其中
id
是一个函数。