Elisp: Reduce (Fold)

By Xah Lee. Date: . Last updated: .

Reduce (aka fold)

seq-reduce

(seq-reduce FUNCTION SEQUENCE INITIAL-VALUE)

  • Recurse a function f of 2 parameters, let's call them state item.
  • Each time,
  • state is the last result of f.
  • item is the new item in SEQUENCE.
  • repeat untill no more items. Return the result.
  • INITIAL-VALUE is used for state when f starts.

For example:

(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"

Example. Implement Pipe Using Reduce

;; -*- coding: utf-8; lexical-binding: t; -*-

(defun xah-pipe (zinit &rest zfunctions)
  "Apply functions to a value.
(xah-pipe x f g h)
computes
(h (g (f x)))
Created: 2025-12-24
Version: 2025-12-24"
  (seq-reduce
   (lambda (xstate xfn) (funcall xfn xstate))
   zfunctions zinit))

;; s------------------------------
;; test

(xah-pipe "abc"
          (lambda (x) (string-replace "a" "1" x))
          (lambda (x) (string-replace "b" "2" x))
          (lambda (x) (string-replace "c" "3" x)))
;; "123"

Elisp, Loop and Iteration

Elisp, sequence functions