State monad and destructive updates

Hi, 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? Thanks, -- Rohit Garg http://rpg-314.blogspot.com/ Graduate Student Applied and Engineering Physics Cornell University

Rohit Garg
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/

On Sun, Mar 18, 2012 at 01:34:30PM -0400, Rohit Garg wrote:
Hi,
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?
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?
Yes, see the ST monad. http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Mon... http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-STRef.... http://hackage.haskell.org/packages/archive/array/latest/doc/html/Data-Array... -Brent
participants (3)
-
Brent Yorgey
-
Ertugrul Söylemez
-
Rohit Garg