Last active
December 15, 2017 22:22
-
-
Save parkeristyping/629c8152e4ab08ac00782e9aca33c5f2 to your computer and use it in GitHub Desktop.
Surprises
This file contains hidden or 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
;; 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