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

Brent Yorgey byorgey at seas.upenn.edu
Tue May 22 04:18:34 CEST 2012


> 
> As you can see, this just selects all elements at particular tree level.
> 
> So, my foldMapS2 looks similar to foldMap from Foldable, but i can't
> figure out, how should i define instances of Foldable (and Monoid?)
> to achieve the same functionality?

You cannot.  Foldable is not general enough; it does not allow you to
define folds which can observe the *structure* of the container being
folded over (such as the level in a tree, the number of children of a
given node, etc.).  It corresponds to simply "flattening" the
structure into a list of elements, turning each of them into a value
of some monoid, and then applying mconcat.

However, you should be able to define a general fold for Tape, with
type

  foldTape :: (a -> [b] -> b) -> Tape a -> b

and then define foldMapS2 in terms of foldTape.

-Brent



More information about the Beginners mailing list