2

我声明我的数据是这样的:

data Op = Plus | Minus | Mul | Div | Pow
        deriving (Eq, Show)

type Name = String

data Variable a = Variable Name (Expression a)
            deriving (Eq, Show)

data Declaration a = Declaration (Variable a)
            deriving (Eq, Show)  

{- The core symbolic manipulation type -}
data Expression a = 
          Number a           -- Simple number, such as 5
        | Expression Op (Expression a) (Expression a)
          deriving (Eq, Show)

在 GHCi 中,我想通过键入来创建声明的实例: Declaration Variable "var1" 2+3 但它不起作用,我想这只是一个错误的语法,但我不知道如何。

另外我想知道我们什么时候需要使用实例?这是我从书中得到的代码:

instance Num a => Num (Expression a) where
    a + b = Expression Plus a b
    a - b = Expression Minus a b
    a * b = Expression Mul a b
    negate a = Expression Mul (Number (-1)) a
    abs a = error "abs is unimplemented"
    signum _ = error "signum is unimplemented"
    fromInteger i = Number (fromInteger i)
4

1 回答 1

5
Declaration Variable "var1" 2+3

相当于

(Declaration Variable "var1" 2) + 3

. 也就是说,它尝试Declaration使用 3 个参数(Variable"var1"2)进行调用,然后将结果添加到3. 这是没有意义的。

你要

Declaration (Variable "var1" (2+3))
于 2013-02-26T03:14:34.013 回答