Xah Talk Show 2025-10-25 Ep706 Fold and Reduce, in Wolfram Language, Emacs Lisp, JavaScript

xah talk show ep706 wl Fold
xah talk show ep706 wl Fold

Video Summary (AI Generated, Reviewed by Human)

This video explains fold (also known as reduce) in functional programming. The creator highlights that fold/reduce is a general way to represent any loop you would typically use in imperative languages (2:25, 9:54, 11:13, 34:21).

Here's a breakdown of the key points:



xah talk show ep706 Wolfram language Fold 2025-10-25 33ac4
xah talk show ep706 Wolfram language Fold 2025-10-25 33ac4
// loop , is fundamental in programing languages.
// typically , in prodecural programing language , aka imperative languages, the most popular way of loop is the for loop.
for (let i = 0; i < 9; i++) {
console.log( i )
}

// now in functional programing languages, the most well known form of loop is via map function
[1,2,3,4].map( ((x) => { console.log( x )}) )

// but, map is not a general purpose loop
// because , for example , if you are given a list, and you want to skip every other element, and apply a function to only those.
 // in this case, you can not use map, usually, because, you do not have the index of the element.
// (in JavaScript, it actualy can do this because the function also receives the index )

// now, the functional programing form of a general purpose loop, is fold, aka reduce .
// it passes the previous state to the function

}
Range[6]
(* {1, 2, 3, 4, 5, 6} *)

Fold[f, {1, 2, 3, 4, 5, 6} ]
(* f[f[f[f[f[1, 2], 3], 4], 5], 6] *)

Fold[f, {1, 2, 3} ]
(* f[f[1, 2], 3] *)

Fold[f, {1, 2, 3, 4} ]
(* f[f[f[1, 2], 3], 4] *)

Fold[f, 0, {1, 2, 3, 4} ]
(* f[f[f[f[0, 1], 2], 3], 4] *)

(* HHHH------------------------------ *)

FoldList[f, {1, 2, 3, 4} ]
(* 
{1,
f[1, 2],
f[f[1, 2], 3],
f[f[f[1, 2], 3], 4]
}
 *)
const xarray = ["1","2","3","4","5"]
const xresult = xarray. reduce( ((a,b) => (a+b)) )
console.log( xresult )
// 12345

// xarray. reduce( ((a,b) => (a+b)), initialValue )

const xx = [1, 2, 3, 4];
const f = ((x, y) => `f(${x},${y})`);
console.log(xx.reduce(f) === "f(f(f(1,2),3),4)");
// true
(setq xx (vector "a" "b" "c"))

(seq-reduce
 (lambda (x y) (concat x y))
 xx
 "")
;; "abc"

fold, reduce