Skip to content

Instantly share code, notes, and snippets.

@emanjavacas
Last active May 31, 2016 08:42
Show Gist options
  • Save emanjavacas/cdacdac8313a533915417a57d53dc7fd to your computer and use it in GitHub Desktop.
Save emanjavacas/cdacdac8313a533915417a57d53dc7fd to your computer and use it in GitHub Desktop.
Clojure Zipper Lazy Visitors
(require 'clojure.zip :as zip)
;;; see also
;;; https://gist.github.com/luxbock/4a4cafdcf2522ede6575
;;; http://stackoverflow.com/a/11426326
(defn depth-first [loc]
(take-while (complement zip/end?) (iterate zip/next loc)))
;;; (peek PQueue) -> head
;;; (pop PQueue) -> but head
;;; (conj PQueue x) -> append
(defn- zip-children [loc]
(when-let [child (zip/down loc)]
(take-while (complement nil?) (iterate zip/right child))))
(defn breadth-first [loc]
((fn bfs [queue]
(lazy-seq
(when (seq queue)
(let [new-loc (peek queue)
children (zip-children new-loc)]
(cons new-loc (bfs (into (pop queue) children)))))))
(conj clojure.lang.PersistentQueue/EMPTY loc)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment