4

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.

4
  • 1
    +1 from me for not having an SO account and asking such a nicely formatted, phrased and tagged question. Sep 27, 2011 at 15:00
  • 1
    You are missing parentheses around 2+3. Additionally, You have to add an instance of Num to your Expr type.
    – fuz
    Sep 27, 2011 at 15:04
  • 3
    Just for fun: ideone.com/WsAk5
    – Ramon Snir
    Sep 27, 2011 at 15:49
  • Additional fun (generics): ideone.com/mw762 Sep 27, 2011 at 17:48

2 Answers 2

5

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)
2
  • 1
    I see, thanks for that suggestion. I was under the impression that ':' would serve as an infix constructor. I really don't want anyone to make my homework for me but what would it take to make the function size take (2+3) as the parameter. Is my definition of Expr wrong or the function size itself?
    – tvd
    Sep 27, 2011 at 15:33
  • 3
    @user967306: Nothing's wrong about those, (2 + 3) simply isn't an Expr, it's an integer (well, actually Num a => a). If you want to construct an Expr tree, you have to explicitly use those constructors (save clever tricks like making Expr an instance of Num and defining fromInteger = Lit and (+) = (:+:), which are likely not intended to do and which may be bad for clarity in any case - but see Ramon's comment for how it's done).
    – user395760
    Sep 27, 2011 at 15:43
0

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.