|
|
|
|
|
by kian
2472 days ago
|
|
If you think of 'reduce' as instead 'accumulating' a value, then it takes a function that adds a single element to the accumulation, and a base accumulation to use if the list is empty, and a list, and returns an accumulation of all of the elements of the list in a directional (in this case right-to-left) order. (accumulate plus 0 lst) is equivalent to (sum lst) (accumulate multiply 1 lst) is equivalent to (product lst) (accumulate (lambda (x acc)
(cons (fn x) acc)) '() lst) is equivalent to (map fn lst) (accumulate (lambda (x acc) (if (fn x) (cons x acc) acc))) '() lst) is equivalent to (filter fn lst) and so forth. The essential insight is that reduce/fold/accumulate reduces the problem of accumulation to a base accumulation and a function that only has to add a single item (i/o)nto the accumulated value. Using them to directionally processes a container is idiomatic in a functional style. |
|