Created
April 24, 2018 21:18
-
-
Save eigenhombre/5d091bee12b93e877479535fbd9e7afb to your computer and use it in GitHub Desktop.
Teaching lazy sequences, etc. ... examples from Clojurepalooza
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
| (def xs (vector 1 2 3)) | |
| (type xs) | |
| (type (map str xs)) | |
| (type (map odd? xs)) | |
| (type (filter odd? (list 1 2 3))) | |
| (first (map str (range))) | |
| (take 10 (range)) | |
| (take 10 (map str (range))) | |
| (take 10 (map str (drop 1000000 (range)))) | |
| (take 10 (map str (iterate inc 0))) | |
| (take 10 (iterate (partial * 2) 1)) | |
| (take 10 (iterate (fn [x] (* 2 x)) 1)) | |
| (count (str (last (take 1000 (iterate (fn [x] (*' 2 x)) 1))))) | |
| (defn eager-range [max-value] | |
| (loop [xs [] | |
| n 0] | |
| (if (< n max-value) | |
| (recur (conj xs n) (inc n)) | |
| xs))) | |
| (take 5 (eager-range 10)) | |
| (defn meager-range | |
| ([]) | |
| ([max-value] | |
| (meager-range max-value 0)) | |
| ([max-value current] | |
| (if (< current max-value) | |
| (cons current (meager-range max-value (inc current))) | |
| nil))) | |
| (cons 0 | |
| (cons 1 | |
| (cons 2 | |
| (cons 3 | |
| (cons 4 | |
| (cons 5 | |
| (cons 6 | |
| (cons 7 | |
| (cons 8 | |
| (cons 9 nil)))))))))) | |
| (meager-range) | |
| (range) ;; Don't do this | |
| (meager-range 10) | |
| (meager-range 10 0) | |
| (defn lazy-range | |
| ([] | |
| (let [inner (fn inner [current] | |
| (lazy-seq | |
| (cons current (inner (inc current)))))] | |
| (inner 0))) | |
| ([max-value] | |
| (lazy-range max-value 0)) | |
| ([max-value current] | |
| (lazy-seq | |
| (if (< current max-value) | |
| (cons current (lazy-range max-value (inc current))) | |
| nil)))) | |
| (defn lazy-inf-range [] | |
| (let [inner (fn inner [current] | |
| (lazy-seq | |
| (cons current (inner (inc current)))))] | |
| (inner 0))) | |
| (type (lazy-range 10)) | |
| (type (lazy-range)) | |
| (count (take 10000000 (lazy-range))) | |
| (count (take 5 (meager-range 10000))) ;; blows up | |
| ;; Problem for next time: | |
| (defn my-iterate [f val] | |
| (lazy-seq | |
| ;; You be the judge of what should go here... | |
| )) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment