Skip to content

Instantly share code, notes, and snippets.

@jclaggett
Created August 21, 2010 19:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jclaggett/542719 to your computer and use it in GitHub Desktop.
Save jclaggett/542719 to your computer and use it in GitHub Desktop.
(defmacro lazy
"Returns a lazy sequence of calls to (f). Arguments are evaluated once as needed.
(lazy f a b c d) --> (a, (f a b), (f (f a b) c), (f (f (f a b) c) d))"
([f x]
`(lazy-seq
(list ~x)) )
([f x form & more]
`(lazy-seq
(let [x# ~x]
(cons x#
(lazy ~f (~f x# ~form) ~@more)))) ) )
(defmacro lazy-> [& args] `(lazy -> ~@args))
(defmacro lazy->> [& args] `(lazy ->> ~@args))
(def ex1 (lazy + 1 2 3 4 5 6))
(def ex2 (lazy * 1 2 3 4 5 6))
(def ex3 (lazy-> 1 (+ 1) (+ 4) (- 2)))
(def ex4
(lazy->>
(#(do (println "(Evaluating first)") 1))
(#(do (println "(Evaluating second)") (+ 1 %)))
(#(do (println "(Evaluating third)") (- 2 %)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment