How to modify just one field of a record without rewriting it completely? [duplicate]

两盒软妹~` 提交于 2019-12-14 03:56:08

问题


It's the second time I'm tackling this problem... And for the second time this is while working with the State monad, apparently a state likes to consist of many fields, not just one

I have a tuple:

type CurrentState = (Int, Int, String, [Int], CustType1, CustType2, CustType3 )

Assume a simple transformation of this tuple is needed... The second Int is a sort of counter, it needs to be incremented:

let incrementCounter currState@(foo, bar, baz, fizz, buzz, blah, yadda) =
    ( foo, bar+1, baz, fizz, buzz, blah, yadda )

Wow. Lots of typing. Now since incrementing the counter is not the only possible operation of this tuple, then clearly there will be many more functions of this kind... The clutter soon becomes annoying.

And what if we change the tuple to a record?

data CurrentState = CurrentState { foo :: Int, bar :: Int, baz :: String,
                                   fizz :: [Int], buzz :: CustType1,
                                   blah :: CustType2, yadda :: CustType 3 }

Incrementing the counter is now even worse!

let incrementCounter currState =
    CurrentState { foo = foo currState, bar = (bar currState) + 1,
                   baz = baz currState, fizz = fizz currState,
                   buzz = buzz currState, blah = blah currState,
                   yadda = yadda currState }

This is kind of amazing. All I want to do is what I'd write in an imperative language as currState.bar += 1;. What is the typical Haskell solution for this kind of problems? Is there any way that would allow me to not rewrite all fields that don't change?


回答1:


You can write such update as:

oldrecord { somefield = newvalue }

so in your case, you can write it like:

let incrementCounter cs@(CurrentState{bar=b}) = cs {bar = b+1}

You can also make use of lens for more advanced updates.



来源:https://stackoverflow.com/questions/55837998/how-to-modify-just-one-field-of-a-record-without-rewriting-it-completely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!