1

我有一组简单的状态,如下所示:

st1 = [("x", 2), ("y", 3), ("z", 3)]

我想在程序运行时更新它,因为值会改变。我有这样的更新代码:

update str val st = (str, val) : foldr step [] st where
    step x acc
        | fst x == str = acc
        | otherwise = x:acc

我想做一个这样的分配函数:

assign (str, val) env = update str val env

我遇到的问题是,由于 Haskell 没有副作用,我更新的列表不会保持更新。关于如何做到这一点的任何想法或建议?

如果我输入解释器

let st2 = update "x" 1 st1

然后保存新的状态。

我想要这个功能来做到这一点:

update "x"  1 st1

Before:   [("x",1),("y",3),("z",3)]

After:    [("y",1),("x",2),("z",3)]
4

1 回答 1

2

正如您已经提到的,您不能在 Haskell 中产生副作用。相反,您可能有多个let表达式(或任何其他类型的定义)。

let st2 = update "x" 1 st1
let st3 = update "y" 2 st2

虽然有一种方法称为State Monad,但我现在不建议深入研究它,因为这个概念并不简单,相反,我建议开始阅读一些 haskell 教程或书籍,你肯定会遇到本教程后面章节中的状态单子。或者甚至比这两种选择更好,自己发明状态单子(这比听起来容易)!

于 2012-11-28T12:37:23.957 回答