实例显示 - 无法编译

时间:2016-01-08 19:01:12

标签: haskell

我在大学里遇到过这个问题:

data Expression a = Constant a 
                | Simetric (Expression a) 
                | Addition (Expression a) (Expression a) 
                | Subtraction (Expression a) (Expression a) 
                | Multiplication (Expression a) (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.

有人可以解释一下我的代码中有什么问题吗?我星期一有期末考试。谢谢你的帮助!

1 个答案:

答案 0 :(得分:3)

你应该阅读编译器的消息,因为它很难提供帮助。

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