[Haskell-cafe] questions on lazy pattern, StateT monad

Wolfgang Jeltsch wolfgang at jeltsch.net
Thu Nov 24 15:03:34 EST 2005

Am Donnerstag, 24. November 2005 01:49 schrieb Fan Wu:
> Hi Wolfgang,
> Thanks for your response and examples! It helps a lot.
> From your example I can see "Lazy patterns are useful in contexts
> where infinite data structures are being defined recursively" (quote
> section 4.4 of Gentle Introduction to Haskell).

They are useful not only in conjunction with infinite data structures.  Take 
my example state transformer "everything" and modify it so that it calls next 
exactly two times, not infinitely many times, and outputs a pair of the 
outputs of the two next invocations.

Now let's assume you use this pair in a context where only its first component 
is used.  Without lazy patterns, next would be invoked two times although it 
need to be invoked only one time.  So you might have unnecessary evaluation.  
And you might have something even worse.  Let's assume that when we apply the 
function making up next on the output state of the first next invocation then 
we get _|_.  Without lazy patterns, just using the output of the first next 
invocation would result in your program aborting.  Of course, it shouldn't do 

> But does it apply to the mplus case? I mean the mplus in (mplus m1 m2) and
> the mplus in (mplus m1' m2') are different due to the difference of Monads
> (one is StateT s m, the other is just m). If I change the mplus inside lift
> to something else like:  
>   mplus m1 m2       = do s <- peek
>                          let m1' = runState s m1
>                              m2' = runState s m2
>                          ~(a,s') <- lift (other_func m1' m2')
>                          poke s'
>                          return a
> Is it still required that (a,s') be lazy?

I thought a bit about the lazy pattern in the mplus implementation and still 
don't know if it's necessary. :-(

> I just want to see how things works in an less obvious example like this
> one.
> Thanks,
> Fan

Best wishes,

More information about the Haskell-Cafe mailing list