[Haskell-cafe] using the writer monad to better understand foldl
and foldr, and haskell debugging techniques in general
tphyahoo at gmail.com
Sun Feb 10 18:52:55 EST 2008
same behavior with
myfoldrD (:)  [1..] -- uses Debug.Trace.trace
So, I would say this proves my main point, which was that you could
accomplish the same thing using the writer monad that you could do
using the more "ad hoc" trace function from Debug.Trace.
It's good that you point this out though, because understanding that
foldr can take an infinite list and foldl not is a very key point.
> 2008/2/10, Felipe Lessa <felipe.lessa at gmail.com>:
> > On Feb 10, 2008 9:33 PM, Thomas Hartman <tphyahoo at gmail.com> wrote:
> > > -- using writer monad
> > > -- Nothing unsafe here, pure referrentially transparent goodness
> > > myfoldrW f z  = return z
> > > myfoldrW f z (x:xs) = do
> > > r <- (myfoldrW f z xs)
> > > tell ("x,r: " ++ (show (x,r)) ++ "\n" )
> > > return $ x `f` r
> > *Main> foldr const 0 [1..]
> > 1
> > *Main> putStrLn $ snd $ runWriter $ myfoldrW const 0 [1..]
> > Interrupted.
> > One of the good things from foldr is the possibility of
> > "short-circuiting", so to speak. However I don't know if it is
> > possible to show this using the writer monad, as is would involve
> > observing if the function is strict or not in its second argument.
> > Cheers,
> > --
> > Felipe.
More information about the Haskell-Cafe