没有(Show([(String,Int)] - > Int)的实例)

时间:2012-10-16 17:24:36

标签: parsing haskell lambda happy

如果我使用lambda表达式,

在生产规则中快速计算表达式的值是不行的。

例如此代码

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 }
来自http://www.haskell.org/happy/doc/html/sec-using.html

无效。

或者更准确地说我收到了错误消息

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

如果你能解释一下我必须改变什么,那就太好了。

它必须与lambda表达式和环境变量p。

有关

当我使用数据类型时,一切都很好。

1 个答案:

答案 0 :(得分:8)

此处需要注意的是,此解析器的结果是函数,它采用了变量绑定的环境。错误消息基本上是GHCi告诉你它无法打印功能,大概是因为你忘了传递环境

> eval "1 + 1"

何时应该传递一个空的环境

> eval "1 + 1" []

或具有一些预定义变量的

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