[英]Haskell: Data Type
I declare my data to be like this: 我声明我的数据是这样的:
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)
In GHCi, I want to create a instance of Declaration by typing: Declaration Variable "var1" 2+3
but it does not work, I guess it is just a wrong syntax, but I cannot figure out how. 在GHCi中,我想通过键入以下内容来创建一个声明的实例: Declaration Variable "var1" 2+3
但是它不起作用,我猜这只是一个错误的语法,但是我不知道怎么做。
Also I would like to know when we need to use instance? 我也想知道何时需要使用实例? This is the code I got from a book: 这是我从书中得到的代码:
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)
Declaration Variable "var1" 2+3
is equivalent to 相当于
(Declaration Variable "var1" 2) + 3
. 。 That is, it tries to call Declaration
with 3 arguments ( Variable
, "var1"
, 2
), then adds the result to 3
. 也就是说,它尝试使用3个参数( Variable
, "var1"
, 2
)调用Declaration
,然后将结果添加到3
。 This makes no sense. 这是没有道理的。
You want 你要
Declaration (Variable "var1" (2+3))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.