【问题标题】:updating a associated list in Haskell更新 Haskell 中的关联列表
【发布时间】: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"。)

标签: list haskell tuples


【解决方案1】:

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

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

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

【讨论】:

  • @BenFossen,如果您想要更多关于创建自己的 State Monad 的参考资料,请询问,我将提供进一步的阅读/解决方案。
猜你喜欢
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 2015-03-29
  • 2021-12-25
  • 2014-01-16
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多