Re:Why I Prefer Functional Programming
by kian on Thursday September 19, 2019 @04:30PM
(#21020415)
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.
Re:Why I Prefer Functional Programming
by saagarjha on Friday September 20, 2019 @02:45AM
(#21023834)
C++ even calls it std::accumulate. (There’s a std::reduce in C++17, but it’s just std::accumulate with the restriction that the operation is commutative.)
(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.