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

烈酒焚心 提交于 2019-12-25 04:57:09

问题


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:


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


来源:https://stackoverflow.com/questions/12920205/no-instance-for-show-string-int-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!