Last active
May 31, 2016 08:42
-
-
Save emanjavacas/cdacdac8313a533915417a57d53dc7fd to your computer and use it in GitHub Desktop.
Clojure Zipper Lazy Visitors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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