List 在Haskell中更新关联列表

List 在Haskell中更新关联列表,list,haskell,tuples,List,Haskell,Tuples,我有一组简单的状态,如下所示: 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 我想在程序运行时更新它,因为值会改变。我有如下

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

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
我想在程序运行时更新它,因为值会改变。我有如下更新代码:

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
我想做一个赋值函数,如下所示:

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)]

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


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

旁注:您可以对
步骤
声明使用模式匹配,并且仍然保留对整个
x
元组的引用,即
step x@(first,)acc | first==str=acc |否则=x:acc
。(这是一个。)@BenFossen,如果你想要更多关于创建自己的州单子的参考资料,请询问,我将提供进一步的阅读/解决方案。