简体   繁体   中英

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.

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 . This makes no sense.

You want

Declaration (Variable "var1" (2+3))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM