Reputation: 111
I'm working on a function that can count the number of operators used in an expression. My code is as follows:
data Expr = Lit Int |
Expr :+: Expr |
Expr :-: Expr
size :: Expr -> Int
size (Lit n) = 0
size (e1 :+: e2) = 1 + (size e1) + (size e2)
size (e1 :-: e2) = 1 + (size e1) + (size e2)
But when I try to execute this code using Hugs98 i get the following error:
Main> size 2+3
ERROR - Cannot infer instance
*** Instance : Num Expr
*** Expression : size 2 + 3
Can somebody tell me what I'm doing wrong? I'm really out of idea's myself.
Upvotes: 4
Views: 1783
Reputation: 1
You can make it a Num instance:
instance Num Expr where
(+) = (:+:)
(-) = (:-:)
negate = (0 -)
fromInteger = Lit . fromInteger
(*) = error "not implemented"
abs = error "not implemented"
signum = error "not implemented"
Once that is in place, size (2+3)
will work (note the parenthesis).
Upvotes: 0
Reputation: 94329
2+3
is not a valid expression. With your types, primtive values are created using the Lit
data constructor, and the valid operators are :+:
and :-:
. So what you really need is Lit 2 :+: Lit 3
. So try
size (Lit 2 :+: Lit 3)
Upvotes: 5