【发布时间】:2012-11-28 11:58:35
【问题描述】:
我有这样一组简单的状态:
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)]
【问题讨论】:
-
旁注:您可以对
step声明使用模式匹配,并且仍然保留对整个x元组的引用,即step x@(first,_) acc | first == str = acc | otherwise = x:acc。 (这称为"as-pattern"。)