[Haskell-cafe] Proposed "Restructuring" of State Monad page in Haskell Wikibooks

Olaf Klinke olf at aatal-apotheke.de
Tue Sep 29 21:17:16 UTC 2020

> Hello – I’m proposing to restructure this<
> https://en.wikibooks.org/wiki/Haskell/Understanding_monads/State>;,
> and I have a draft here<
> https://en.wikibooks.org/wiki/Davjam2:Example/StateMonad>;. I’ve
> given my main reasons for the restructuring at the top of the draft
> page.
> I’d very much like feedback before updating the real page, especially
> if people don’t like the new one much.

+1 for the new version by David. 

In addition to the content already present, I'd like to see examples
(and exercises! these are great!) of State used with other common
monadic combinators. You covered sequence, but what about mapM a.k.a.
traverse, what about foldM? Can filterM be put to good use with state
You could introduce another type 
TurnstileInput = Push | Coin
and combine pushS, coinS into a single function of type 
TurnstileInput -> State TurnstileState TurnstileOutput
which can be used in mapM. Your exercises of different people can then
be implemented as mapM of a single function (namely the FSM) over
finite sequences of TurnstileInputs. 

As a side-note, Data.Traversable.mapAccumR is implemented using a
StateR that passes the state backwards. Only an Applicative instance is
given in Data.Functor.Utils. I wonder whether this is a lawful monad or
not. The comment says so, but I don't see how. 

Here is a departure from the otherwise very concrete and down-to-earth
explanation of State, but a fun exercise nevertheless: Implement return
and (>>=) for 
type State s a = s -> (s,a) 
using the following two functions and the Functor instance of ((->) s).

iso :: ((s,a) -> b) -> a -> s -> b
iso uncurried = curry (uncurried . Data.Tuple.swap)
iso' :: (a -> s -> b) -> (s,a) -> b -- inverse of iso
iso' curried = uncurry (flip curried)


More information about the Haskell-Cafe mailing list