philipbohun.com

Glojure by Example: Sequences

Most collections can be viewed as a sequence. map, filter, and reduce walk that view. map and filter return a lazy sequence, which println realizes.

(println (map inc [1 2 3]))
(println (filter odd? [1 2 3 4]))
(println (reduce + 0 [1 2 3 4]))

range with no end is infinite and lazy. take keeps the first few elements. for is a list comprehension, not a loop statement. :when filters as it goes.

(println (take 3 (range)))
(println (for [x [1 2]
               :when (odd? x)
               y [10 20]]
           (+ x y)))

some returns the first truthy result. Strings are sequences of characters, and rest works on vectors by viewing them as a sequence.

(println (some even? [1 3 4]))
(println (first "abc"))
(println (rest [10 20 30]))

Lazy sequences print as lists once they are realized.

$ glj sequences.glj
(2 3 4)
(1 3)
10
(0 1 2)
(11 21)
true
a
(20 30)

Next example: Functions.