Number of operators in an expression - Unable to display an example

I am working on a function that can count the number of statements 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 someone tell me what I'm doing wrong? I myself am really not myself.

+4
source share
2 answers

2+3 not a valid expression. With your types, primitive values โ€‹โ€‹are created using the Lit data constructor, and the actual operators are :+: and :-: So you really need Lit 2 :+: Lit 3 . Therefore try

 size (Lit 2 :+: Lit 3) 
+5
source

You can make an instance of Num:

 instance Num Expr where (+) = (:+:) (-) = (:-:) negate = (0 -) fromInteger = Lit . fromInteger (*) = error "not implemented" abs = error "not implemented" signum = error "not implemented" 

Once this is done, size (2+3) will work (note the brackets).

0
source

All Articles