| 
 
I struggle to understand Traversable
 Haskell evolved a lot since the last time I seriously wrote any
Haskell code, so much so that all my old programs broke.  My Monad
instances don't compile any more because I'm no longer allowed to
have a monad which isn't also an instance of Applicative.  Last time I used
Haskell, Applicative wasn't even a thing.  I had read the McBride and
Paterson paper that introduced applicative functors, but that was
years ago, and I didn't remember any of the details.  (In fact, while
writing this article, I realized that the paper I read was a preprint,
and I probably read it before it was published, in 2008.)  So to
resuscitate my old code I had to implement a bunch of <*>functions
and since I didn't really understand what it was supposed to be doing
I couldn't do that.  It was a very annoying experience. Anyway I got that more or less under control (maybe I'll publish a
writeup of that later) and moved on to Traversable which, I hadn't realized
before, was also introduced in that same paper.  (In the
prepublication version, Traversable had been given the unmemorable name
IFunctor.)  I had casually looked into this several times in the
last few years but I never found anything enlightening.  A Traversable is a
functor (which must also implement Foldable, but let's pass over that
for now, no pun intended) that implements atraversemethod with the
following signature:     traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
 The traversable functor itself here is t.  Thefthing is an
appurtenance.  Often one looks at the type of some function and says “Oh, that's what
that does”, but I did not get any understanding from this signature. The first thing to try here is to make it less abstract.  I was
thinking about Traversable this time because I thought I might want
it for a certain type of tree structure I was working with.  So I
defined an even simpler tree structure:     data Tree a = Con a | Add (Tree a) (Tree a)
        deriving (Eq, Show)
 Defining a bunch of other cases wouldn't add anything to my
understanding, and it would make it take longer to try stuff, so I
really want to use the simplest possible example here.  And this is
it: one base case, one recursive case. Then I tried to make this type it into a Traversable instance.  First we need
it to be a Functor, which is totally straightforward:     instance Functor Tree where
        fmap f (Con a) = Con (f a)
        fmap f (Add x y) = Add (fmap f x) (fmap f y)
 Then we need it to be a Foldable, which means it needs to provide a
version of foldr.  The old-fashionedfoldrwas     foldr :: (a -> b -> b) -> b -> [a] -> b
 but these days the list functor in the third place has been generalized:     foldr :: Foldable f => (a -> b -> b) -> b -> f a -> b
 The idea is that foldr fncollapses a list ofas into a singlebvalue by feeding in theas one at a time.  Each time,foldrtakes
the previousband the currentaand constructs a newb. The
second argument is the initial value ofb.
Another way to think about it is that every list has the form     e1 : e2 : .... : []
 and foldr fn bapplied to this list replaces the(:)calls withfnand the trailing[]withb, giving me     e1 `f` e2 `f` .... `f` b
 The canonical examples
for lists are:     sum = foldr (+) 0
 (add up the elements, starting with zero) and     length = foldr (\_ -> (+ 1)) 0
 (ignore the elements, adding 1 to the total each time, starting with
zero).  Also foldr (:) []is the identity function for lists because
it replaces the(:)calls with(:)and the trailing[]with[]. Anyway for Treeit looks like this:    instance Foldable Tree where
        foldr f b (Con a) = f a b
        foldr f b (Add x y) = (foldr f) (foldr f b x) y
 The Conclause says to take the constant value and combine it with
the default total. TheAddclause says to first fold up the
left-side subtreexto a single value, then use that as the initial
value for folding up the right-side subtreey, so everything gets
all folded up together.  (We could of course do the right subtree
before the left; the results would be different but just as good.) I didn't write this off the top of my head, I got it by following the
types, like this: 
In the first clause     foldr f b (Con a) = ???
 we have a function fthat wants anavalue and
abvalue, and we have both anaand ab, so put the tabs in the
slots.In the second clause      foldr f b (Add x y) = ???
 fneeds anavalue and none is available, so we can't usefby itself.  We can only use it recursively viafoldr.  So forgetf, we will only be dealing only withfoldr f, which has typeb -> Tree a -> b.  We need to apply this to abvalue and the
only one we have isb, and then we need to apply that to one of
the subtrees, sayx, and thus we have synthesized thefoldr f b xsubexpression.  Then pretty much the same process
gets us the rest of it: we need aband the only one we have now
isfoldr f b x, and then we need another tree and the only one we
haven't used isy.
 It turns out it is easier and more straightforward to write foldMapinstead, but I didn't know that at the time. I won't go into it
further because I have already digressed enough.  The preliminaries
are done, we can finally get on to the thing I wanted, the Traversable:     instance Traversable Tree where
      traverse = ....
 and here I was stumped.  What is this supposed to actually do?
For our Treefunctor it has this signature:     traverse :: Applicative f => (a -> f b) -> Tree a -> f (Tree b) 
 Okay, a function a -> f bI understand, it turns each tree leaf
value into a list or something, so at each point of the tree it gets
out a list ofbs, and it potentially has one of those for each item
in the input tree.  But how the hell do I turn a tree of lists into
a single list ofTree b?  (The answer is that the secret sauce is
in the Applicative, but I didn't understand that yet.) I scratched my head and read a bunch of different explanations and
none of them helped.  All the descriptions I found were in either
prose or mathematics and I still couldn't figure out what it was for.
Finally I just wrote a bunch of examples and at last the light came
on.  I'm going to show you the examples and maybe the light will come
on for you too. We need two Traversable functors to use as examples.  We don't have a Traversable
implementation for Treeyet so we can't use that.  When I think of
functors, the first two I always think of areListandMaybe, so
we'll use those.     > traverse (\n -> [1..n]) Nothing
    [Nothing]
    > traverse (\n -> [1..n]) (Just 3)
    [Just 1,Just 2,Just 3]
 Okay, I think I could have guessed that just from the types.  And
going the other way is not very interesting because the output, being
a Maybe, does not have that much information in it.     > let f x = if even x then Just (x `div` 2) else Nothing
 If the !!x!! is even then the result is just half of !!x!!, and
otherwise the division by 2 “fails” and the result is nothing.
Now:     > traverse f [ 1, 2, 3, 4 ]
    Nothing
    > traverse f [ 10, 4, 18 ]
    Just [5,2,9]
 It took me a few examples to figure out what was going on here: When
all the list elements are even, the result is Justa list of half of
each.  But if any of the elements is odd, that spoils the whole result
and we getNothing.  (traverse f []isJust []as one would
expect.) That pretty much exhausts what can be done with lists and maybes.  Now
I have two choices about where to go next: I could try making both
functors List, or I could use a different functor entirely.  (Making
bothMaybeseemed like a nonstarter.)  UsingListtwice seemed
confusing, and when I tried it I could kinda see what it was doing but
I didn't understand why.  So I took a third choice: I worked up a Traversable
instance forTreejust by following the types even though I didn't
understand what it ought to be doing.  I thought I'd at least see if I
could get the easy clause:     traverse :: Applicative f => (a -> f b) -> Tree a -> f (Tree b) 
    instance Traversable Tree where
      traverse fn (Con a) = ...
 In the ...I havefn :: a -> f band I have at hand a singlea.  I need to
construct aTree b.  The only way to get abis to applyfnto
it, but this gets me anf band I needf (Tree b).  How do I get theTreein there?  Well, that's whatConis for, gettingTreein
there, it turns atintoTree t.  But how do I do that inside off?  I tinkered around a little bit and eventually found   traverse fn (Con a) = Con <$> (fn a)
 which not only type checks but looks like it could even be correct.
So now I have a motto for what <$>is about: if I have some
function, but I want to use it inside of some applicative functorf, I can apply it with<$>instead of with$. Which, now that I have said it myself, I realize it is exactly what
everyone else was trying to tell me all along: normal function
application takes an a -> band applies to to anagiving ab.
Applicative application takes anf (a -> b)and applies it to anf agiving anf b.  That's what applicative functors are all about,
doing stuff inside off. Okay, I can listen all day to an explanation of what an electric
drill does, but until I hold it in my hand and drill some holes I
don't really understand. Encouraged, I tried the hard clause:   traverse fn (Add x y) = ...
 and this time I had a roadmap to follow:   traverse fn (Add x y) = Add <$> ...
 The Conclause hadfn aat that point to produce anf bbut that won't
work here because we don't have ana, we have a wholeTree a, and we
don't need anf b, we need anf (Tree b).  Oh, no problem,traverse fnsupposedly turns aTree ainto anf (Tree b), which
is just what we want.
And it makes sense to have a recursive call totraversebecause this is the
recursive part of the recursive data structure:   traverse fn (Add x y) = Add <$> (traverse fn x) ...
 Clearly traverse fn yis going to have to get in there somehow, and
since the pattern for all the applicative functor stuff is   f <$> ... <*> ... <*> ...
 let's try that:   traverse fn (Add x y) = Add <$> (traverse fn x) <*> (traverse fn y)
 This looks plausible.  It compiles, so it must be doing something.
Partial victory!  But what is it doing?  We can run it and see, which
was the whole point of an exercise: work up a Traversable instance for Treeso that I can figure out what Traversable is about. Here are some example trees:  t1 = Con 3                              -- 3
 t2 = Add (Con 3) (Con 4)                -- 3 + 4
 t3 = Add (Add (Con 3) (Con 4)) (Con 2)  -- (3 + 4) + 2
 (I also tried Add (Con 3) (Add (Con 4) (Con 2))but it did not
contribute any new insights so I will leave it out of this article.) First we'll try Maybe.  We still have thatffunction from before:     f x = if even x then Just (x `div` 2) else Nothing
 but traverse f t1,traverse f t2, andtraverse f t3only produceNothing, presumably because of the odd numbers in the trees.  One
odd number spoils the whole thing, just like in a list. So try:     traverse f (Add (Add (Con 10) (Con 4)) (Con 18))
 which yields:           Just (Add (Add (Con 5) (Con 2)) (Con 9))
 It keeps the existing structure, and applies fat each value
point,  just likefmap, except that iffever returnsNothingthe whole computation is spoiled and we getNothing.  This is
just like whattraverse fwas doing on lists. But where does that spoilage behavior come from exactly?  It comes
from the overloaded behavior of <*>in the Applicative instance ofMaybe:  (Just f) <*> (Just x) = Just (f x)
 Nothing  <*> _        = Nothing
       _  <*> Nothing  = Nothing
 Once we get a Nothingin there at any point, theNothingtakes
over and we can't get rid of it again. I think that's one way to think of traverse: it transforms each
value in some container, just likefmap, except that wherefmapmakes all its transformations independently, and reassembles the exact
same structure, withtraversethe reassembly is done with the
special Applicative semantics.  ForMaybethat means “oh, and if at any
point you getNothing, just give up”. Now let's try the next-simplest Applicative, which is List.  Say,     g n = [ 1 .. n ]
 Now traverse g (Con 3)is[Con 1,Con 2,Con 3]which is not exactly
a surprise buttraverse g (Add (Con 3) (Con 4))is something that
required thinking about:     [Add (Con 1) (Con 1),
     Add (Con 1) (Con 2),
     Add (Con 1) (Con 3),
     Add (Con 1) (Con 4),
     Add (Con 2) (Con 1),
     Add (Con 2) (Con 2),
     Add (Con 2) (Con 3),
     Add (Con 2) (Con 4),
     Add (Con 3) (Con 1),
     Add (Con 3) (Con 2),
     Add (Con 3) (Con 3),
     Add (Con 3) (Con 4)]
 This is where the light finally went on for me.  Instead of thinking
of lists as lists, I should be thinking of them as choices.  A list
like [ "soup", "salad" ]means that I can choose soup or salad, but
not both.  A functiong :: a -> [b]says, in restauranta, whatbs are on the menu. The gfunction says what is on the menu at each node.  If a node has
the number 4, I am allowed to choose any of[1,2,3,4], but if it has
the number 3 then the choice 4 is off the menu and I can choose only
from[1,2,3]. Traversing gover aTreemeans, at each leaf, I am handed a menu,
and I make a choice for what goes at that leaf.  Then the result oftraverse gis a complete menu of all the possible complete trees I
could construct. Now I finally understand how the tand thefswitch places in     traverse :: Applicative f => (a -> f b) -> t a -> f (t b) 
 I asked “how the hell do I turn a tree of lists into a single list
of Tree b”?  And that's the answer: each list is a local menu of
dishes available at one leaf, and the result list is the global menu
of the complete dinners available over the entire tree. Okay!  And indeed traverse g (Add (Add (Con 3) (Con 4)) (Con 2))has
24 items, starting       Add (Add (Con 1) (Con 1)) (Con 1)
      Add (Add (Con 1) (Con 1)) (Con 2)
      Add (Add (Con 1) (Con 2)) (Con 1)
      ...
 and ending       Add (Add (Con 3) (Con 4)) (Con 1)
      Add (Add (Con 3) (Con 4)) (Con 2)
 That was traversing a list function over a Tree.  What if I go the
other way?  I would need an Applicative instance forTreeand I didn't
really understand Applicative yet so that wasn't going to happen for a
while.  I know I can't really understand Traversable without understanding
Applicative first but I wanted to postpone the day of reckoning as long as
possible. What other functors do I know?  One easy one is the functor that takes
type aand turns it into type(String, a).  Haskell even has a
built-in Applicative instance for this, so I tried it:      > traverse (\x -> ("foo", x)) [1..3]
     ("foofoofoo",[1,2,3])                     
     > traverse (\x -> ("foo", x*x)) [1,5,2,3]
     ("foofoofoofoo",[1,25,4,9])
 Huh, I don't know what I was expecting but I think that wouldn't have
been it.  But I figured out what was going on: the built-in Applicative
instance for the a -> (String, a)functor just concatenates the
strings.  In general it is defined ona -> (m, b)whenevermis a
monoid, and it doesfmapon the right component and uses monoid
concatenation on the left component.  So I can use integers instead of
strings, and it will add the integers instead of concatenating the
strings.  Except no, it won't, because there are several ways to make
integers into a monoid, but each type can only have one kind of
Monoid operations, and if one was wired in it might not be the one I
want.  So instead they define a bunch of types that are all integers
in obvious disguises, just labels stuck on them that say “I am not an
integer, I am a duck”; “I am not an integer, I am a potato”.  Then
they define different overloadings for “ducks” and “potatoes”.  Then
if I want the integers to get added up I can put duck labels on my
integers and if I want them to be multiplied I can stick potato labels
on instead.  It looks like this:    import Data.Monoid
   h n = (Sum 1, n*10)
 Sumis the duck label.  When it needs to combine two
ducks, it will add the integers:
    > traverse h [5,29,83]
   (Sum {getSum = 3},[50,290,830]) 
 But if we wanted it to multiply instead we could use the potato label,
which is called Data.Monoid.Product:     > traverse (\n -> (Data.Monoid.Product 7, 10*n)) [5,29,83]
    (Product {getProduct = 343}, [50,290,830])                                                                                        
 There are three leaves, so we multiply three sevens and get 343. Or we could do the same sort of thing on a Tree:     > traverse (\n -> (Data.Monoid.Product n, 10*n)) (Add (Con 2) (Add (Con 3) (Con 4)))
    (Product {getProduct = 24}, Add (Con 20) (Add (Con 30) (Con 40)))               
 Here instead of multiplying together a bunch of sevens we multiply
together the leaf values themselves. The McBride and Paterson paper spends a couple of pages talking about
traversals over monoids,  and when I saw the example above it started
to make more sense to me.  And their ZipListexample became clearer
too.  Remember when we had a function that gave us a menu at every
leaf of a tree, andtraverse-ing that function over a tree gave us a
menu of possible trees?        > traverse (\n -> [1,n,n*n]) (Add (Con 2) (Con 3))
       [Add (Con 1) (Con 1),
        Add (Con 1) (Con 3),
        Add (Con 1) (Con 9),
        Add (Con 2) (Con 1),
        Add (Con 2) (Con 3),
        Add (Con 2) (Con 9),
        Add (Con 4) (Con 1),
        Add (Con 4) (Con 3),
        Add (Con 4) (Con 9)]
 There's another useful way to traverse a list
function.  Instead of taking each choice at each leaf we make a
single choice ahead of time about whether we'll take the first,
second, or third menu item,  and then we take that item every time:     > traverse (\n -> Control.Applicative.ZipList [1,n,n*n]) (Add (Con 2) (Con 3))
    ZipList {getZipList = [Add (Con 1) (Con 1),
                           Add (Con 2) (Con 3),
                           Add (Con 4) (Con 9)]}
 There's a built-in instance for Either a balso.  It's a lot likeMaybe.Rightis likeJustandLeftis likeNothing.  If all
the sub-results areRight ythen it rebuilds the structure with all
theys and gives backRight (structure).  But if any of the
sub-results isLeft xthen the computation is spoiled and it gives
back the firstLeft x.  For example:  > traverse (\x -> if even x then Left (x `div` 2) else Right (x * 10)) [3,17,23,9]
 Right [30,170,230,90]                
 > traverse (\x -> if even x then Left (x `div` 2) else Right (x * 10)) [3,17,22,9]
 Left 11
 Okay, I think I got it. Now I just have to drill some more holes. 
 
[Other articles in category /prog/haskell] 
permanent link
 
 |