Elisp: Sequence Iteration

By Xah Lee. Date: . Last updated: .

Sequence Iteration Guide

Reduce (Fold, Accumulator)

Reduce is a general way to do loop in functional programing style. A function is feed args from a list, and each time, the result is feed back to the function.

It solves the problem of storing value in a global variable or keeping state, such as a increment counter. By passing the state to the function.

seq-reduce

(seq-reduce FUNCTION SEQUENCE INITIAL-VALUE)

Recurse a function of 2 parameters x y, each time feed x the last result, feed y the new item in sequence, till no more items. Return the result.

start with putting INITIAL-VALUE in x.

For example:

  • (seq-reduce f [1] 0) → (f 0 1)
  • (seq-reduce f [1 2] 0) → (f (f 0 1) 2)
  • (seq-reduce f [1 2 3] 0) → (f (f (f 0 1) 2) 3)
(setq xx (vector "a" "b" "c"))

(seq-reduce
 (lambda (x y) (concat x y))
 xx
 "")
;; "abc"
(setq xx (vector "a" "b" "c"))

(seq-reduce
 (lambda (x y) (concat x y))
 (seq-drop xx 1)
 (seq-first xx))

;; "abc"

Elisp, Loop and Iteration

Elisp, sequence functions

Elisp, Vector