开发者

Count number of operators in an expression - Cannot infer instance

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 e开发者_运维百科xecute 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+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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜