Skip to content

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.

emacs-lisp
(-iterate #'1+ 1 10)
    ⇒ (1 2 3 4 5 6 7 8 9 10)
emacs-lisp
(-iterate (lambda (x) (+ x x)) 2 5)
    ⇒ (2 4 8 16 32)
emacs-lisp
(--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.

emacs-lisp
(-unfold (lambda (x) (unless (= x 0) (cons x (1- x)))) 10)
    ⇒ (10 9 8 7 6 5 4 3 2 1)
emacs-lisp
(--unfold (when it (cons it (cdr it))) '(1 2 3 4))
    ⇒ ((1 2 3 4) (2 3 4) (3 4) (4))
emacs-lisp
(--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.

emacs-lisp
(-repeat 3 :a)
    ⇒ (:a :a :a)
emacs-lisp
(-repeat 1 :a)
    ⇒ (:a)
emacs-lisp
(-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.

emacs-lisp
(-take 5 (-cycle '(1 2 3)))
    ⇒ (1 2 3 1 2)
emacs-lisp
(-take 7 (-cycle '(1 "and" 3)))
    ⇒ (1 "and" 3 1 "and" 3 1)
emacs-lisp
(-zip-lists (-cycle '(3)) '(1 2))
    ⇒ ((3 1) (3 2))