[Haskell-beginners] State monad and destructive updates

Ertugrul Söylemez es at ertes.de
Sun Mar 18 20:21:37 CET 2012


Rohit Garg <rpg.314 at gmail.com> wrote:

> As I have been trying to learn the monads a bit more, I have come to
> realize that State monad doesn't actually represent state. It just
> provides a convenient glue for threading state. Is that correct? If
> so, then for performance using state monad is as good as not using it
> at all. Is there a way to have state with destructive update?

There are things like STRefs and ST arrays.  However, note that you only
need destructive update if you have to update only a relatively small
portion of a strict (!) data structure (like individual elements in an
array).  In all other cases just go with a state monad or recursion.
You won't lose performance there.

Most pure data structures don't count here.  For example updating maps,
sets or other ADT-based data structures does not need to copy anything.
It just updates its references and is done.  The penalty is a small
constant or logarithmic factor.

This is one reason why you would generally prefer nonstrict boxed data
structures.  Nonstrict boxing makes slower imperative code, but faster
functional code.

Often when your intuition tells you that you need destructive update for
performance, it will be wrong.  Remember that Haskell is a lazy
language.  If you are unsure how to solve a particular problem purely,
free free to ask.


Greets,
Ertugrul

-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120318/d4b99cde/attachment.pgp>


More information about the Beginners mailing list