[Haskell-beginners] State Monad: how to use other Stateful computation on sub-state inside

martin martin.drautzburg at web.de
Fri Oct 16 20:28:47 UTC 2015


Hello all,

I found myself writing this piece of code:

-- | Create and add a new 'Item' to the system
sysAddItem :: ItmLabel -> ItmVolume -> ItmCapacity -> Position -> Instant
           -> State System ItmId

sysAddItem lbl vol cap pos t = do
    sys  <- get
    id   <- sysNextId :: State System Id

    itms' <- return $ execState  (itmAdd' (Itm id lbl vol cap pos t)) (sysItems sys) --**

    modify (\sys -> sys{sysItems=itms'})
    return id


In the lonely line ** in the middle I use

	itmAdd' :: Item -> State ItemDb (),

where the ItemDb is part of the  'System' and can be extracted via sysItems. I believe this code is correct, but I don't
like it.

The expression to the right of <- must have the type

	State System ItemDb

But ItemAdd' has the type

	Item -> State ItemDb ()

So I need to transform

	(Item -> State ItemDb ()) to (State System ItemDb).

There is no question that I have to pass the Item, but the transformation of the States is quite noisy. Is there a
better way to make this transformation, given a function System->ItemDb (i.e. sysItems)?


More information about the Beginners mailing list