Reputation: 115
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)
Upvotes: 2
Views: 214
Reputation: 85757
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))
Upvotes: 5