Skip to content

Instantly share code, notes, and snippets.

@parkeristyping
Last active December 15, 2017 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parkeristyping/629c8152e4ab08ac00782e9aca33c5f2 to your computer and use it in GitHub Desktop.
Save parkeristyping/629c8152e4ab08ac00782e9aca33c5f2 to your computer and use it in GitHub Desktop.
Surprises
;; This is a collection of code that surprised me.
;;
;; Example 1
;;
(let [counter (atom 0)
coll [(swap! counter inc)]]
[(take 1 coll) @counter])
;;=> [(1) 1]
(let [counter (atom 0)
coll (lazy-cat [(swap! counter inc)])]
[(take 1 coll) @counter])
;;=> [(1) 0]
;; Explanation -> `take` preserves laziness, so we aren't actually realizing anything
;; in `coll` until printing the output. The `deref` of `counter` happens before that.
;;
;; Example 2
;;
(def lazy-boys
(let [lazy-boy (lazy-seq (cons (throw (Exception. "oh no")) '()))]
(repeatedly
#(try
(doall lazy-boy)
(catch Exception e
{:message (.getMessage e)})))))
(take 2 lazy-boys)
;;=> ({:message "oh no"} {:message "oh no"})
(def lazy-boyz
(let [lazy-boy (lazy-cat [(throw (Exception. "oh no"))])]
(repeatedly
#(try
(doall lazy-boy)
(catch Exception e
{:message (.getMessage e)})))))
(take 2 lazy-boyz)
;;=> ({:message "oh no"} ())
;; Explanation -> idk yet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment