Collecting values from Functors?

Ralf Laemmel Ralf.Laemmel@cwi.nl
Wed, 04 Jun 2003 21:05:32 +0200


Graham Klyne wrote:
> 
> I'm trying to figure if there's any way I can use (say) monads to collect
> values from a Functor.
> 
> For example, suppose I have a tree of some values that supports fmap, is
> there any way I can use the fmap function to collect a list of all the node
> values?

Rather than using fmap, why not use gmap in GHC.
Using an appropriate generic traversal scheme,
say listify, all the code you write is the
following expression:

listify (const True) mytree :: [Int]

if you are looking for all the Ints in
mytree = Fork (Leaf 42) (Fork (Leaf 88) (Leaf 37))
So this would give you [42,88,37].

(So you do not need to force your datatypes to become
functors, neither do you write Functor instances.)

I added this example to the boilerplate page.
http://www.cs.vu.nl/boilerplate/

Ralf

-- 
Ralf Laemmel
VU & CWI, Amsterdam, The Netherlands
http://www.cs.vu.nl/~ralf/
http://www.cwi.nl/~ralf/