News for hackers. Stuff that matters.
Re:State Monad for the Rest of Us by Iceland_jack on Friday August 09, 2024 @11:14AM (#41202661)
Any function matching the type

    St -> (a, St)
can viewed as `State St' parameterized over `a'. There are several behaviors that organize such functions, such as Monad which "overloads the semicolon" to work on stateful computations. Another behavior implements a stateful interface: `MonadState St'.

    get :: St -> (St, St)
    put :: St -> (St -> ((), St))
With type classes in Haskell, behaviour is type-directed so in order to reap the benefits we declare a new type.

    {-# Language DerivingVia #-}
    {-# Language GADTSyntax  #-}

    -- get :: My St
    -- put :: St -> My ()
    newtype My a where
      My :: (St -> (a, St)) -> My a
      deriving (Functor, Applicative, Monad, MonadState St, MonadFix)
      via State St
Re:State Monad for the Rest of Us by greener_grass on Friday August 09, 2024 @11:40AM (#41202908)
Is there are correct way around?

    St -> (a, St)
vs

    St -> (St, a)
I've found both in the wild and it can be very confusing!
Re:State Monad for the Rest of Us by chuckadams on Friday August 09, 2024 @11:47AM (#41202957)
The order doesn’t matter as long as you’re consistent, but Control.Monad.State uses the first, and you’ll have a bad time (in Haskell anyway) if you’re not compatible with that.
Re:State Monad for the Rest of Us by RandomThoughts3 on Friday August 09, 2024 @12:51PM (#41203483)
It’s the same thing. Order doesn’t matter in the tuple. Just use a bind which is in line with the signature of the type you want to use.