gpt4 book ai didi

haskell - 模拟评估者

转载 作者:行者123 更新时间:2023-12-02 10:18:40 25 4
gpt4 key购买 nike

我正在使用 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 有什么问题,有人可以向我解释一下吗?

最佳答案

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,无论输入如何。

关于haskell - 模拟评估者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39542434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com