2016-09-17 74 views
3

我使用Haskell模拟评估者。它应该很简单,但我无法调试。模拟评估者

这里我定义State作为查找功能(String -> Int),初始状态(empty,异常变量评估0),并extend添加新键(和它的值)为base环境:

type State = String -> Int 

extend :: State -> String -> Int -> State 
extend base key val = \x -> if key == x 
           then val 
           else base key 

empty :: State 
empty = \x -> 0 

当我测试程序:

aState = extend empty "A" 5 
bState = extend aState "B" 4 
cState = extend bState "C" 3 

我想这cState应相当于一个功能:

\x -> if x == "C" 
      then 3 
      else if x == "B" 
        then 4 
        else if x == "A" 
          then 5 
          else 0 

但是相反,我得到cState "B" == 0cState "A" == 0

我看不出extend有什么问题,有人可以向我解释吗?

回答

6

在您的else声明中,您在每次递归中搜索key(而不是x):else base key。与修复:

extend :: State -> String -> Int -> State 
extend base key val = \x -> if key == x 
           then val 
           else base x 

顺便说一句,你可能会这样写:

empty :: State 
empty = \_ -> 0 

因为empty回报0无论输入的。