Skip to content

Instantly share code, notes, and snippets.

@mhuebert
Last active August 29, 2015 14:26
Show Gist options
  • Select an option

  • Save mhuebert/858e4ecf2ee72cb69cc3 to your computer and use it in GitHub Desktop.

Select an option

Save mhuebert/858e4ecf2ee72cb69cc3 to your computer and use it in GitHub Desktop.
; in clojure an if-then statement looks like: (if test do-this-if-true do-this-if-false)
; eg (if has-water (prn "content") (water-plant))
(defn find-replace [zipper pred replacement]
(loop [loc zipper] ;begin a loop - when we call `recur` at the bottom,this is where we come back to.
(if (z/end? loc) ;if we are at the end, it means we've visited every node, so...
(root loc) ;we return the zipper
(if
(pred loc) ;`pred` is a function that we supply as a "test" for each location. eg. is this an 'x'?
(recur (z/next (z/replace loc (replacement loc)))) ;this is what we do if `pred` returned true
(recur (z/next loc)))))) ; this is what we do if `pred` returned false
; example usage of this `find-replace` function
(let [my-zipper (z/of-string "(+ 1 2 (- 4 3))") ;make a zipper out of a string of clojure code
multiply-by-ten (fn [element] (* 10 element))]
(find-replace my-zipper even? multiply-by-ten))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment