Unfolding
Operations dual to reductions, building lists from a seed value rather than consuming a list to produce a single value.
Function: -iterate (fun init n)
Return a list of iterated applications of fun to init.
This means a list of the form:
(init (fun init) (fun (fun init)) …)
n is the length of the returned list.
(-iterate #'1+ 1 10)
⇒ (1 2 3 4 5 6 7 8 9 10)(-iterate (lambda (x) (+ x x)) 2 5)
⇒ (2 4 8 16 32)(--iterate (* it it) 2 5)
⇒ (2 4 16 256 65536)Function: -unfold (fun seed)
Build a list from seed using fun.
This is "dual" operation to -reduce-r (see -reduce-r): while -reduce-r consumes a list to produce a single value, -unfold (see -unfold) takes a seed value and builds a (potentially infinite!) list.
fun should return nil to stop the generating process, or a cons (a . b), where a will be prepended to the result and b is the new seed.
(-unfold (lambda (x) (unless (= x 0) (cons x (1- x)))) 10)
⇒ (10 9 8 7 6 5 4 3 2 1)(--unfold (when it (cons it (cdr it))) '(1 2 3 4))
⇒ ((1 2 3 4) (2 3 4) (3 4) (4))(--unfold (when it (cons it (butlast it))) '(1 2 3 4))
⇒ ((1 2 3 4) (1 2 3) (1 2) (1))Function: -repeat (n x)
Return a new list of length n with each element being x. Return nil if n is less than 1.
(-repeat 3 :a)
⇒ (:a :a :a)(-repeat 1 :a)
⇒ (:a)(-repeat 0 :a)
⇒ ()Function: -cycle (list)
Return an infinite circular copy of list. The returned list cycles through the elements of list and repeats from the beginning.
(-take 5 (-cycle '(1 2 3)))
⇒ (1 2 3 1 2)(-take 7 (-cycle '(1 "and" 3)))
⇒ (1 "and" 3 1 "and" 3 1)(-zip-lists (-cycle '(3)) '(1 2))
⇒ ((3 1) (3 2))