3

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 Answers1

6

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555