[Haskell-cafe] mdo with multiple values
Joachim Breitner
mail at joachim-breitner.de
Wed Jan 15 23:24:05 UTC 2014
Dear John,
the background is a binary format assembler, so you can think of the
monad as the Put monad, only sufficiently lazy to admit a useful
MonadFix instance. Then one can do nice things like
mdo
putWord32 offset
putBS someMoreHeaderData
...
offset <- getCurrentOffset
putBS byteString1
where I conceptually use the offset before it is known.
So what if I want to put two offsets, followed by two bytestrings? Easy:
mdo
putWord32 offset1
putWord32 offset2
putBS someMoreHeaderData
...
offset1 <- getCurrentOffset
putBS byteString1
offset2 <- getCurrentOffset
putBS byteString2
Now I try to generalize that to a list of Bytestrings, and just from the
looks of it, this is what you want to do:
mdo
mapM_ putWord32 offsets
putBS someMoreHeaderData
...
offsets <- forM byteStrings $ \b ->
offset <- getCurrentOffset
putBS b
return offset
but that will <<loop>>.
Am Mittwoch, den 15.01.2014, 13:10 -0800 schrieb John Lato:
> Hello Joachim,
> I don't really understand what you're doing here. There's the obvious
>
> mapM_ (act2 >=> act1)
>
> But presumably act1 performs some monadic action that doesn't depend
> on its input, and you need that to be performed before act2?
Exactly, (act2 >=> act1) would write out the data in the wrong order.
> To me, it feels like there's some sort of implicit coupling between
> act1 and act2, and you would be better off extracting that, perhaps by
> changing act1 to have the type act1 :: M T -> () .
>
> If that's not possible, your approach seems pretty simple to me.
I don’t think its, possible with that signature, no...
(It were if I were to interleave the calls to act1 and act2, instead of
requiring first all act1 and then all act2, but then it would be trivial
anyways.)
Greetings,
Joachi
--
Joachim Breitner
e-Mail: mail at joachim-breitner.de
Homepage: http://www.joachim-breitner.de
Jabber-ID: nomeata at joachim-breitner.de
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: This is a digitally signed message part
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20140115/a434c7c8/attachment.sig>
More information about the Haskell-Cafe
mailing list