[Haskell-beginners] Re: State monad question

Heinrich Apfelmus apfelmus at quantentunnel.de
Thu Jun 24 03:20:55 EDT 2010


Jordan Cooper wrote:
> Secondly, as to why I wanted to use a monad here, importantFunction
> (which is called playerTurn in the real program) would contain a
> series of functions that would modify Cards and Players, not just one
> each as in my initial example. Thus it seems like I'd have to end up
> with let foo... let foo'... etc. which, from my reading in RWH, seems
> to be an acceptable use for a State monad.

While your use of the state monad may well be sensible, keep in mind 
that many cases of "threading state" are covered by ordinary functional 
programming idioms, like function composition

     process = take 3 . sort . map length . filter (not . null) . lines

and accumulating parameters

     average xs = foldl' step (0,0) xs
         where
         step (!s,!n) x = (s+x, n+1)

     reverse xs = go xs
         where
         go ys []     = ys
         go ys (x:xs) = go (x:ys) xs

The functions in  Data.Map  are a good example as well: most of them 
"change" the map, but a state monad would be overkill for that.


The state monad is mainly beneficial when you otherwise would have many 
functions of type

     :: s -> (a,s)

with ugly plumbing like

     let (a,s') = foo s; (b,s'') = foo s' in ..


Regards,
Heinrich Apfelmus

--
http://apfelmus.nfshost.com



More information about the Beginners mailing list