Skip to content

Instantly share code, notes, and snippets.

@zelark
Created April 27, 2020 19:42
Show Gist options
  • Save zelark/893cbe18694988eb4cf230ffa51a8a63 to your computer and use it in GitHub Desktop.
Save zelark/893cbe18694988eb4cf230ffa51a8a63 to your computer and use it in GitHub Desktop.
(defn eager-map [f coll]
(when-first [x coll]
(println "iteration")
(cons (f x)
(eager-map f (rest coll)))))
(defn lazy-map [f coll]
(lazy-seq
(when-first [x coll]
(println "iteration")
(cons (f x)
(lazy-map f (rest coll))))))
(defn lazy-filter [pred coll]
(lazy-seq
(when-first [x coll]
(if (pred x)
(cons x (lazy-filter pred (rest coll)))
(lazy-filter pred (rest coll))))))
(defn lazy-filter' [pred coll]
(lazy-seq
(when-let [s (seq coll)]
(let [fst (first s)
rst (rest s)]
(if (pred fst)
(cons fst (lazy-filter' pred rst))
(lazy-filter' pred rst))))))
(first (filter #(trace (even? %)) [42 2 3 5 7]))
(first (lazy-filter #(trace (even? %)) [42 2 3 5 7]))
(first (lazy-filter' #(trace (even? %)) [42 2 3 5 7]))
(defn sieve [n]
(letfn [(divisor-of? [m] #(zero? (rem % m)))
(step [[x & xs]]
(lazy-seq (cons x
(step (remove (divisor-of? x) xs)))))]
(take n (step (nnext (range))))))
(defn lazy-bomb [[x & xs]]
(letfn [(step [[y & ys]]
(lazy-seq
(when y (cons y (step ys)))))]
(lazy-seq
(when x (cons x (lazy-bomb (step xs)))))))
(let [x (for [n (range)] (make-array Object 10000))
f (^:once fn* [] (nth x 1e6))]
(f))
(let [x (for [n (range)] (make-array Object 10000))
f (fn* [] (nth x 1e6))]
(f))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment