[Haskell-beginners] Traverse tree with computing current level using Foldable instance.

Brent Yorgey byorgey at seas.upenn.edu
Thu May 24 14:54:23 CEST 2012


On Thu, May 24, 2012 at 03:09:24PM +0400, Dmitriy Matrosov wrote:
> 
> and the last one with monadic go function and monadic user-defined folding
> function:
> 
> > foldTapeD2 :: (Monoid m) => (a -> State Int m) -> Tape a -> m
> > foldTapeD2 f t          = fst $ runState (foldTape (go f) t) 0
> >   where
> >     go :: (Monoid m) =>
> >           (a -> State Int m) -> a -> [State Int m] -> State Int m
> >     go f name xs        = do
> >                             cs <- get
> >                             z <- f name
> >                             put (cs + 1)
> >                             foldr (go' (cs + 1)) (return z) xs
> >     go' :: (Monoid m) => Int -> State Int m -> State Int m -> State Int m
> >     go' cs mx mz        = do
> >                             x <- mx
> >                             put cs
> >                             z <- mz
> >                             put cs
> >                             return (x `mappend` z)

By the way, for this sort of pattern where you change the state for
some subcomputation and then restore it after the subcomputation
returns, it can be much nicer to use the Reader monad with the 'local'
function instead of the State monad.  That might actually go a long
way towards making the monadic version nicer to read. =)

-Brent



More information about the Beginners mailing list