0

我有一个快速的问题。Haskell 向我抛出 57 - Undefined variable "f" 错误,我不知道为什么。如果你能看看这个,我将不胜感激。代码:

eval :: Expr -> Environment -> Float
eval expr env = eval' expr
    where
    eval' :: Expr-> Float
    eval' (Num num) = num
    eval' (App app exprs) = foldl1 (f) (map eval' exprs) -- **Line 57**
    eval' (Id id) = 5
        where
        f = getFunctionForApp app                    -- **f is here** 
        getFunctionForApp :: String -> (Float->Float->Float)
        getFunctionForApp "+" = (+)
        getFunctionForApp "-" = (-)
        getFunctionForApp "*" = (*)
        getFunctionForApp "/" = (/)
        getIdVal :: String -> Environment -> Float
        getIdVal id ((curId, val):envrs) 
            |curId == id = val
            | otherwise = getIdVal id envrs

类型定义:

data Expr = Num Float | Id String | App String [ Expr ]
           deriving (Eq, Ord, Show)
type Environment = [ ( String, Float ) ]
4

2 回答 2

11

我真的不能说,但在尝试解密代码后,我猜你的意思如下:

eval :: Expr -> Environment -> Float
eval expr env = eval' expr 
    where eval' :: Expr -> Float 
          eval' (Num num) = num 
          eval' (App app exprs) = foldl1 (f) (map eval' exprs)
              where f = getFunctionForApp app -- that has to be in this line
          eval' (Id id) = 5 

(现在有了格式化的代码,我确定就是这样。where子句仅适用于子句之前的行)

于 2012-05-15T08:03:00.143 回答
10

问题是内部where子句附加到该行

eval' (Id id) = 5

但上面的行需要它

eval' (App app exprs) = foldl1 (f) (map eval' exprs) -- **Line 57**

通常,函数定义的每一行都有自己的范围。where子句可以引用它所附加的行中的模式变量,并且仅作用于该行的其余部分。

于 2012-05-15T08:20:00.167 回答