No instance for (Show ([(String, Int)] -> Int))

1.4k Views Asked by At

to calculate the value of the expression on the fly at the production rules in happy doesn't work if I'm using the lambda expressions.

For example this code

Exp   : let var '=' Exp in Exp  { \p -> $6 (($2,$4 p):p) }
      | Exp1                    { $1 }

Exp1  : Exp1 '+' Term           { \p -> $1 p + $3 p }
      | Exp1 '-' Term           { \p -> $1 p - $3 p }
      | Term                    { $1 }

Term  : Term '*' Factor         { \p -> $1 p * $3 p }
      | Term '/' Factor         { \p -> $1 p `div` $3 p }
      | Factor                  { $1 }

Factor            
      : int                     { \p -> $1 }
      | var                     { \p -> case lookup $1 p of
                                    Nothing -> error "no var"
                                     Just i  -> i }
      | '(' Exp ')'             { $2 }

from http://www.haskell.org/happy/doc/html/sec-using.html doesn't work.

Or more precisly I 've got an error message

No instance for (Show ([(String, Int)] -> Int))
      arising from a use of `print'
    Possible fix:
      add an instance declaration for (Show ([(String, Int)] -> Int))
    In a stmt of an interactive GHCi command: print it

It would be nice if you could explain me what I have to change.

It must have something to do with the lambda expression and the environment variable p.

When I'm using data types everything is fine.

1

There are 1 best solutions below

0
On

The thing to note here is that the result of this parser is a function which takes an environment of variable bindings. The error message is basically GHCi telling you that it can't print functions, presumably because you forgot to pass an environment

> eval "1 + 1"

when you should have either passed an empty environment

> eval "1 + 1" []

or one with some pre-defined variables

> eval "x + x" [("x", 1)]