| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
1 parent 4cd176a commit 6e691ec
1 file changed
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -1,3 +1,5 @@ | |||
| 1 | + (ns clojure-through-code.06a-lazy-evaluation) | ||
| 2 | + | ||
| 1 | 3 | ;;;;;;;;;;;;;;;;;; | |
| 2 | 4 | ;; Lazy evaluation | |
| 3 | 5 | ||
@@ -12,6 +14,35 @@ | |||
| 12 | 14 | (take 10 (iterate dec 0)) | |
| 13 | 15 | ||
| 14 | 16 | ||
| 17 | + ;; Seeing Lazy evaluation in action | ||
| 18 | + | ||
| 19 | + ;; By creating a lazy sequence | ||
| 20 | + | ||
| 21 | + (defn lazy-random-numbers | ||
| 22 | + "Lazy evaluation of a random number generator, generates only the numbers required at evaluation time. Once a number is generated though, it does not need to be generated again." | ||
| 23 | + [maximum-number] | ||
| 24 | + (lazy-seq | ||
| 25 | + (println "I just created a number in the lazy sequence") | ||
| 26 | + (cons (rand-int maximum-number) | ||
| 27 | + (lazy-random-numbers maximum-number)))) | ||
| 28 | + | ||
| 29 | + (def random-numbers | ||
| 30 | + (take 10 (lazy-random-numbers 100))) | ||
| 31 | + | ||
| 32 | + ;; to see the laziness of the sequence (list of numbers), just take a few of them | ||
| 33 | + | ||
| 34 | + (first random-numbers) | ||
| 35 | + ;; sends 1 println to the REPl | ||
| 36 | + ;; => 36 | ||
| 37 | + | ||
| 38 | + (nth random-numbers 3) | ||
| 39 | + ;; sends 3 println to the REPl | ||
| 40 | + | ||
| 41 | + (count random-numbers) | ||
| 42 | + ;; sends 6 println to the REPl first time this is called | ||
| 43 | + ;; sends 0 println to the REPl all consecutive times as all the numbers are now cached | ||
| 44 | + | ||
| 45 | + | ||
| 15 | 46 | ||
| 16 | 47 | ;;; Move to list section | |
| 17 | 48 | ||
| Back | FazBrowse Home | New Git URL |
0 commit comments