Cab*_*ick 3 haskell functional-programming
我正在用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
Run Code Online (Sandbox Code Playgroud)
当我测试程序时:
aState = extend empty "A" 5
bState = extend aState "B" 4
cState = extend bState "C" 3
Run Code Online (Sandbox Code Playgroud)
我想这cState应该等同于一个函数:
\x -> if x == "C"
then 3
else if x == "B"
then 4
else if x == "A"
then 5
else 0
Run Code Online (Sandbox Code Playgroud)
但是,相反,我得到的cState "B" == 0和cState "A" == 0.
我看不出有什么问题extend,有人可以向我解释一下吗?
在你的else说法,你搜索key(而不是x在每一个递归)else base key.修复它:
extend :: State -> String -> Int -> State
extend base key val = \x -> if key == x
then val
else base x
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你可能写道:
empty :: State
empty = \_ -> 0
Run Code Online (Sandbox Code Playgroud)
因为无论输入如何都empty返回0.
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |