The source for this post is online at 2013-04-01-dfs-in-racket.rkt.
A student came into my office the other day and asked how you would do a tree search (specifically breadth-first search) in Racket. His assumption was that it would be difficult or strange in a primarily functional paradigm. This post recapitulates that experience.
I asked the student for the basic idea of breadth-first search. His answer was, "You have a queue, which you add the root to. You keep taking things off the queue and if you find the node you are looking for, you return it. Otherwise, you add its children to the end of the queue and continue. If the queue is ever empty when you try to remove from it, return an indication of failure."
This algorithm can be directly translated into Racket code, parameterized over the notion of a node:
Given this tree, we would expect the following tests to succeed:
This version of the algorithm, while correct, is a bit unsatisfying because it is extremely imperative and uses an escape continuation, which is a bit complicated. A simpler version is:
This purely functional version is nice, because it more neatly expresses what is going on. Unfortunately, it is inefficient, because append is O(n) in time and space where n is the length of the queue.
A nicer way to do this is to observe that the queue is private state that can’t be observed by the clients of bfs, so it is okay to use an imperative data-structure. But, while doing that, keep the rest of the code structured as the functional version.
Finally, a more Racket-y way to write this would be to use sequences and the for/or macro, rather than write the loop explicitly.
One nice thing about this code is that it is parameterized over the notion of a node. This allows exotic nodes like:
and tests like:
Of course, since this tree is infinite, you shouldn’t try searches that fail, like
Finally, it should be natural for you to adapt this code to use the data/heap library to turn it into a best-first search or a depth-first search.
(require racket/list rackunit racket/function racket/match data/queue) (define-syntax-rule (while cond body ...) (let loop () (when cond body ... (loop)))) (let () <cons-node> (let () <imperative> <example-tests>) (let () <functional> <example-tests>) (let () <simple-imperative> <example-tests>) (let () <simpler-imperative> <example-tests>)) (let () <binary-node> (let () <simpler-imperative> <binary-tests>))