FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Lazy evaluation in action with lazy-seq · whitethief/clojure-through-code@6e691ec · GitHub

Commit 6e691ec

Browse files
Lazy evaluation in action with lazy-seq
1 parent 4cd176a commit 6e691ec

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

‎src/clojure_through_code/06a_lazy_evaluation.clj‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
(ns clojure-through-code.06a-lazy-evaluation)
2+
13
;;;;;;;;;;;;;;;;;;
24
;; Lazy evaluation
35

@@ -12,6 +14,35 @@
1214
(take 10 (iterate dec 0))
1315

1416

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+
1546

1647
;;; Move to list section
1748

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL