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.
2+3is not a valid expression. With your types, primtive values are created using theLitdata constructor, and the valid operators are:+:and:-:. So what you really need isLit 2 :+: Lit 3. So try