Clojure lazy sequences.


(range 2 7)
(range 6)
;; An infinite range:
(take 5 (range))
(class (range 2 7))
(class (range))
(def evens (filter even? (range)))
(take 5 evens)
(take 5 (map #(* % %) evens))

;; how to create your own infinite lazy sequences:
(take 10 (repeat 3))
(take 10 (iterate #(* 2 %) 1))

;; many higher-order functions return lazy sequences:
(take 10 (map inc (iterate #(* 2 %) 1)))
(take 10 (interleave (iterate #(* 2 %) 1) (iterate #(* 3 %) 1)))

;; you can store lazy sequences in variables:
(def all-natural-numbers (range))

;; note: reduce is not lazy (it is eager):
;; this will go into an infinite computation:
;(def sum-of-everything (reduce + (range)))

CSci 4651 course web site.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.