Breadth-First Traversals in Far Too Much Detail

Posted on June 3, 2018

After looking at the algorithms I posted last time, I noticed some patterns emerging which I thought deserved a slightly longer post. I’ll go through the problem (Gibbons 2015) in a little more detail, and present some more algorithms to go along with it.

The Problem

The original question was posed by Etian Chatav:

What is the correct way to write breadth first traversal of a [Tree] ?

The breadth-first traversal here is a traversal in the lensy sense, i.e:

breadthFirst :: Applicative f => (a -> f b) -> [ Tree a] -> f [ Tree b] (af b)a]f [b]

The Tree type we’re referring to here is a rose tree; we can take the one defined in Data.Tree :

data Tree a = Node { rootLabel :: a , subForest :: [ Tree a] a] }

Finally, instead of solving the (somewhat intermediate) problem of traversing a forest, we’ll look directly at traversing the tree itself. In other words, our solution should have the type:

breadthFirst :: Applicative f => (a -> f b) -> Tree a -> f ( Tree b) (af b)f (b)

Breadth-First Enumeration

As in Gibbons (2015), let’s first look at just converting the tree to a list in breadth-first order. In other words, given the tree:

┌3 ┌2┤ │ └4 1┤ │ ┌6 └5┤ └7

We want the list:

[ 1 , 2 , 5 , 3 , 4 , 6 , 7 ]

Last time I looked at this problem, the function I arrived at was as follows:

breadthFirstEnumerate :: Tree a -> [a] [a] = f ts b [] breadthFirstEnumerate tsf ts b [] where Node x xs) fw bw = x : fw (xs : bw) f (x xs) fw bwfw (xsbw) = [] b [][] = foldl ( foldr f) b qs [] b qsf) b qs []

It’s admittedly a little difficult to understand, but it’s really not too complex: we’re popping items off the front of a queue, and pushing the subforest onto the end. fw is the recursive call here: that’s where we send the queue with the element pushed on. Even though it may look like we’re pushing onto the front (as we’re using a cons), this is really the end of the queue, since it’s being consumed in reverse, with foldl .

We can compare it to the technique used in Allison (2006) and Smith (2009), where it’s called corecursive queues. Breadth-first enumeration is accomplished as follows in Smith (2009):

levelOrder :: Tree a -> [a] [a] = map rootLabel qs levelOrder trrootLabel qs where = enqs [tr] 0 qs qsenqs [tr]qs = deq n xs enqs [] n xsdeq n xs : ts) n xs = t : enqs ts (n + 1 ) xs enqs (tts) n xsenqs ts (n) xs 0 _ = [] deq[] : xs) = enqs (subForest x) (n - 1 ) xs deq n (xxs)enqs (subForest x) (n) xs

We get to avoid tracking the length of the queue, however.

Level-Order Enumeration

Before we go the full way to traversal, we can try add a little structure to our breadth-first enumeration, by delimiting between levels in the tree. We want our function to have the following type:

levels :: Tree a -> [[a]] [[a]]

Looking back at our example tree:

┌3 ┌2┤ │ └4 1┤ │ ┌6 └5┤ └7

We now want the list:

1 ],[ 2 , 5 ],[ 3 , 4 , 6 , 7 ]] [[],[],[]]

This function is strictly more powerful than breadthFirstEnumerate , as we can define one in terms of the other:

= concat . levels breadthFirstEnumeratelevels

It’s also just a generally useful function, so there are several example implementations available online.

Iterative-Style

The one provided in Data.Tree is as follows:

= levels t map ( map rootLabel) $ rootLabel) takeWhile ( not . null ) $ iterate ( concatMap subForest) [t] subForest) [t]

Pretty nice, but it looks to me like it’s doing a lot of redundant work. We could write it as an unfold:

= unfoldr (f . concat ) [[t]] levels tunfoldr (f) [[t]] where = Nothing f [] = Just ( unzip [(y,ys) | Node y ys <- xs]) f xs[(y,ys)y ysxs])

The performance danger here lies in unzip : one could potentially optimize that for a speedup.

With an (implicit) Queue

Another definition, in the style of breadthFirstEnumerate above, is as follows:

= f b ts [] [] levels tsf b ts [] [] where Node x xs) ls qs = k (x : ls) (xs : qs) f k (x xs) ls qsk (xls) (xsqs) = [] b _ [][] = k : foldl ( foldl f) b qs [] [] b k qsf) b qs [] []

Here, we maintain a stack building up the current level, as well as a queue that we send to the next level. Because we’re consing onto the front of the stack, the subforest needs to be traversed in reverse, to build up the output list in the right order. This is why we’re using a second foldl here, whereas the original had foldr on the inner loop.

Zippy-Style

Looking at the implicit queue version, I noticed that it’s just using a church-encoded pair to reverse the direction of the fold. Instead of doing both reversals, we can use a normal pair, and run it in one direction:

= b (f ts ([],[])) levels tsb (f ts ([],[])) where Node x xs) (ls,qs) = (x : ls,xs : qs) f (x xs) (ls,qs)(xls,xsqs) = [] b (_,[])[] = k : b ( foldr ( flip ( foldr f)) ([],[]) qs) b (k,qs)b (f)) ([],[]) qs)

Secondly, we’re running a fold on the second component of the pair: why not run the fold immediately, rather than building the intermediate list. In fact, we’re running a fold over the whole thing, which we can do straight away:

= f ts [] levels tsf ts [] where Node x xs) (q : qs) = (x : q) : foldr f qs xs f (x xs) (qqs)(xq)f qs xs Node x xs) [] = [x] : foldr f [] xs f (x xs) [][x]f [] xs

After looking at it for a while, I realized it’s similar to an inlined version of the algorithm presented in Gibbons (2015):

= [rootLabel t] : foldr (lzw ( ++ )) [] ( map levels (subForest t)) levels t[rootLabel t](lzw ()) [] (levels (subForest t)) where : xs) (y : ys) = f x y : lzw f xs ys lzw f (xxs) (yys)f x ylzw f xs ys = xs lzw _ xs []xs = ys lzw _ [] ysys

Cofree

Before going any further, all of the functions so far can be redefined to work on the cofree comonad:

data Cofree f a = a :< f ( Cofree f a) f af (f a)

When f is specialized to [] , we get the original rose tree. So far, though, all we actually require is Foldable .

From now on, then, we’ll use Cofree instead of Tree .

Traversing

Finally, we can begin on the traversal itself. We know how to execute the effects in the right order, what’s missing is to build the tree back up in the right order.

Filling

First thing we’ll use is a trick with Traversable , where we fill a container from a list. In other words:

1 .. ] = ([ 1 , 2 , 3 , 4 ],[ 5 .. ]) fill [(),(),(),()] [([],[])

With the state monad (or applicative, in this case, I suppose), we can define a “pop” action, which takes an element from the supply:

= state (\(x : xs) -> (x,xs)) popstate (\(xxs)(x,xs))

And then we traverse that action over our container:

= traverse ( const pop) fillpop)

When we use fill, it’ll have the following type:

breadthFirst :: ( Applicative f, Traversable t) f,t) => (a -> f b) -> Cofree t a -> f ( Cofree t b) (af b)t af (t b) = ... breadthFirst where ... fill :: t ( Cofree t a) -> State [ Cofree t b] (t ( Cofree t b)) t (t a)t b] (t (t b)) = traverse ( const pop) fillpop)

Hopefully that makes sense: we’re going to get the subforest from here:

data Cofree t a = a :< t ( Cofree t a) t at (t a) ^^^^^^^^^^^^^^

And we’re going to fill it with the result of the traversal, which changes the contents from a s to b s.

Composing Applicatives

One of the nice things about working with applicatives is that they compose, in a variety of different ways. In other words, if I have one effect, f , and another g , and I want to run them both on the contents of some list, I can do it in one pass, either by layering the effects, or putting them side-by-side.

In our case, we need to deal with two effects: the one generated by the traversal, (the one the caller wants to use), and the internal state we’re using to fill up the forests in our tree. We could use Compose explicitly, but we can avoid some calls to pure if we write the combinators we’re going to use directly:

map2 :: ( Functor f, Functor g) f,g) => (a -> b -> c) -> f a -> g b -> f (g c) (ac)f ag bf (g c) = map2 f x xs fmap (\y -> fmap (f y) xs) x (\y(f y) xs) x app2 :: ( Applicative f, Applicative g) f,g) => (a -> b -> c -> d) -> f a -> g b -> f (g c) -> f (g d) (ad)f ag bf (g c)f (g d) = app2 f x xs -> liftA2 (f y) xs) x liftA2 (\yliftA2 (f y) xs) x

The outer applicative ( f ) will be the user’s effect, the inner will be State .

Take 1: Zippy-Style Traversing

First we’ll try convert the zippy-style levels to a traversal. First, convert the function over to the cofree comonad:

= f tr [] levels trf tr [] where :< xs) (q : qs) = (x : q) : foldr f qs xs f (xxs) (qqs)(xq)f qs xs :< xs) [] = [x] : foldr f [] xs f (xxs) [][x]f [] xs

Next, instead of building up a list of just the root labels, we’ll pair them with the subforests:

= f tr [] breadthFirst trf tr [] where :< xs) (q : qs) = ((x,xs) : q) : foldr f qs xs f (xxs) (qqs)((x,xs)q)f qs xs :< xs) [] = [(x,xs)] : foldr f [] xs f (xxs) [][(x,xs)]f [] xs

Next, we’ll fill the subforests:

= f tr [] breadthFirst trf tr [] where :< xs) (q : qs) = ((x,fill xs) : q) : foldr f qs xs f (xxs) (qqs)((x,fill xs)q)f qs xs :< xs) [] = [(x,fill xs)] : foldr f [] xs f (xxs) [][(x,fill xs)]f [] xs

Then, we can run the applicative effect on the root label:

= f tr [] breadthFirst c trf tr [] where :< xs) (q : qs) = ((c x,fill xs) : q) : foldr f qs xs f (xxs) (qqs)((c x,fill xs)q)f qs xs :< xs) [] = [(c x,fill xs)] : foldr f [] xs f (xxs) [][(c x,fill xs)]f [] xs

Now, to combine the effects, we can use the combinators we defined before:

= f tr [] breadthFirst c trf tr [] where :< xs) (q : qs) = f (xxs) (qqs) -> (y :< ys) : zs) (c x) (fill xs) q : foldr f qs xs app2 (\y ys zs(yys)zs) (c x) (fill xs) qf qs xs :< xs) [] = f (xxs) [] -> [y :< ys]) (c x) (fill xs) : foldr f [] xs map2 (\y ys[yys]) (c x) (fill xs)f [] xs

This builds a list containing all of the level-wise traversals of the tree. To collapse them into one, we can use a fold:

breadthFirst :: ( Traversable t, Applicative f) t,f) => (a -> f b) (af b) -> Cofree t a t a -> f ( Cofree t b) f (t b) = breadthFirst c tr head <$> foldr (liftA2 evalState) ( pure []) (f tr []) (liftA2 evalState) ([]) (f tr []) where :< xs) (q : qs) = f (xxs) (qqs) -> (y :< ys) : zs) (c x) (fill xs) q : foldr f qs xs app2 (\y ys zs(yys)zs) (c x) (fill xs) qf qs xs :< xs) [] = f (xxs) [] -> [y :< ys]) (c x) (fill xs) : foldr f [] xs map2 (\y ys[yys]) (c x) (fill xs)f [] xs

Take 2: Queue-Based Traversing

Converting the queue-based implementation is easy once we’ve done it with the zippy one. The result is (to my eye) a little easier to read, also:

breadthFirst :: ( Applicative f, Traversable t) f,t) => (a -> f b) -> Cofree t a -> f ( Cofree t b) (af b)t af (t b) = breadthFirst c tr fmap head (f b tr e []) (f b tr e []) where :< xs) ls qs = f k (xxs) ls qs -> (y :< ys) : zs) (c x) (fill xs) ls) (xs : qs) k (app2 (\y ys zs(yys)zs) (c x) (fill xs) ls) (xsqs) = pure [] b _ [][] = liftA2 evalState l ( foldl ( foldl f) b qs e []) b l qsliftA2 evalState l (f) b qs e []) e = pure ( pure []) [])

There are a couple things to notice here: first, we’re not using map2 anywhere. That’s because in the zippy version we were able to notice when the queue was exhausted, so we could just output the singleton effect. Here, instead, we’re using pure (pure []) : this is potentially a source of inefficiency, as liftA2 f (pure x) y is less efficient than fmap (f x) y for some applicatives.

On the other hand, we don’t build up a list of levels to be combined with foldr (liftA2 evalState) at any point: we combine them at every level immediately. You may be able to do the same in the zippy version, but I haven’t figured it out yet.

Yoneda

The final point to make here is to do with the very last thing we do in the traversal: fmap head . Strictly speaking, any fmap s in the code should be unnecessary: we should be able to fuse them all with any call to liftA2 . This transformation is often called the “Yoneda embedding”. We can use it here like so:

breadthFirst :: ∀ t a f b . ( Traversable t, Applicative f) t a f bt,f) => (a -> f b) -> Cofree t a -> f ( Cofree t b) (af b)t af (t b) = f (b head ) tr e [] breadthFirst c trf (b) tr e [] where :< xs) ls qs = f k (xxs) ls qs -> (y :< ys) : zs) (c x) (fill xs) ls) (xs : qs) k (app2 (\y ys zs(yys)zs) (c x) (fill xs) ls) (xsqs) b :: ∀ x . ([ Cofree t b] -> x) ([t b]x) -> f ( State [ Cofree t b] [ Cofree t b]) f (t b] [t b]) -> [t ( Cofree t a)] [t (t a)] -> f x f x = pure (k []) b k _ [](k []) = b k l qs -> k . evalState x) l ( foldl ( foldl f) (b id ) qs e []) liftA2 (\xevalState x) l (f) (b) qs e []) e = pure ( pure []) [])

Notice that we need scoped type variables here, since the type of b changes depending on when it’s called.

Take 3: Iterative Traversing

Transforming the iterative version is slightly different from the other two:

= fmap head (go [tr]) breadthFirst c tr(go [tr]) where = pure [] go [][] = go xs liftA2 evalState traverse f xs)) (getCompose (f xs)) foldr (\(_ :< ys) b -> foldr ( : ) b ys) [] xs)) (go ((\(_ys) b) b ys) [] xs)) :< xs) = Compose (map2 ( :< ) (c x) (fill xs)) f (xxs)(map2 () (c x) (fill xs))

We’re using Compose directly here, in contrast to the other two algorithms.

Comparison

Performance-wise, no one algorithm wins out in every case. For enumeration, the zippy algorithm is the fastest in most cases—except when the tree had a large branching factor; then, the iterative algorithm wins out. For the traversals, the iterative algorithm is usually better—except for monads with more expensive applicative instances.

I’m still not convinced that the zippy traversal is as optimized as it could be, however. If anyone has a better implementation, I’d love to see it!

Fusion

Using the composability of applicatives, we can fuse several operations over traversables into one pass. Unfortunately, however, this can often introduce a memory overhead that makes the whole operation slower overall. One such example is the iterative algorithm above:

= fmap head (go [tr]) breadthFirst c tr(go [tr]) where = pure [] go [][] = liftA2 evalState zs (go (ys [])) go xsliftA2 evalState zs (go (ys [])) where Compose ( Endo ys, Compose zs) = traverse f xs ys,zs)f xs :< xs) = f (xxs) Compose ( Endo ( flip ( foldr ( : )) xs) )) xs) , Compose (map2 ( :< ) (c x) (fill xs))) (map2 () (c x) (fill xs)))

We only traverse the subforest of each node once now, fusing the fill operation with building the list to send to the recursive call. This is expensive (especially memory-wise), though, and traversing the descendant is cheap; the result is that the one-pass version is slower (in my tests).

Generalizing

The cofree comonad allows us to generalize over the type of “descendants”—from lists (in Tree ) to anything traversable. We could also generalize over the type of the traversal itself: given a way to access the descendants of a node, we should be able to traverse all nodes in a breadth-first order. This kind of thing is usually accomplished by Plated: it’s a class that gives you a traversal over the immediate descendants of some recursive type. Adapting the iterative version is relatively simple:

breadthFirstOf :: Traversal' a a -> Traversal' a a a aa a = fmap head (go [tr]) breadthFirstOf trav c tr(go [tr]) where = pure [] go [][] = go xs liftA2 evalState traverse f xs)) (getCompose (f xs)) foldr (\ys b -> foldrOf trav ( : ) b ys) [] xs)) (go ((\ys bfoldrOf trav () b ys) [] xs)) = Compose ( fmap fill (c xs)) f xsfill (c xs)) = trav ( const ( State (\(x : xs) -> (x, xs)))) filltrav ((\(xxs)(x, xs))))

We can use this version to get back some of the old functions above:

breadthFirstEnumerate :: Traversable f => Cofree f a -> [a] f a[a] = toListOf (breadthFirstOf plate . _extract) breadthFirstEnumeratetoListOf (breadthFirstOf plate_extract)

Unfolding

Building a tree breadth-first, monadically, is still an unsolved problem (it looks like: Feuer 2015).

Using some of these we can implement a monadic breadth-first unfold for the cofree comonad:

unfoldM :: ( Monad m, Traversable t) m,t) => (b -> m (a, t b)) (bm (a, t b)) -> b -> m ( Cofree t a) m (t a) = go head [tr] unfoldM c trgo[tr] where = pure (k []) go k [](k []) = do go k xs <- traverse c xs ysc xs . evalState ( traverse f ys)) (toList ( Compose ( Compose ys))) go (kevalState (f ys)) (toList (ys))) = fmap (x :< ) (fill xs) f (x,xs)(x) (fill xs)

References