Description Arguments Value Usage Details Author(s) References See Also Examples
Apply a function to each element of a sequence and the accumulated value of the previous function applications
x |
Any indexable data structure |
fn |
A binary operator |
acc |
Accumulator |
An object containing the accumulated result.
fold(x, fn, acc, ...) %::% . : Function : . : ... : .
fold(x, fn, acc, ...)
The fold operation is a generalization of the summation and product operators in mathematics. The idea is that the elements of a sequence can have a function applied to them and then can be aggregated in some arbitrary way. In terms of the summation operator, the general structure is sum f(x_i). This means that the function f is applied to each element of x and then added to some intermediate accumulator. This is equivalent to a function f' : A x B -> B where the single function is responsible for both applying f and also aggregating the accumulated value.
A 2D fold is similar to a 2D map in the sense that the function operates on the columns of x. This indicates that fn takes a vector and not a scalar as the first argument. If fn is vectorized, then the behavior of fold will be equivalent to a 2D map over the rows!
Brian Lee Yung Rowe
Haskell Wiki, http://www.haskell.org/haskellwiki/Fold
Brian Lee Yung Rowe, Modeling Data With Functional Programming In R.
1 2 3 4 5 6 7 8 9 10 11 12 | x <- 1:10
# This is equivalent to the summation operator
sum(x) == fold(x, function(a,b) a+b, 0)
sum(x^2) == fold(x, function(a,b) a^2 + b, 0)
# This is equivalent to the product operator
prod(x) == fold(x, function(a,b) a*b, 1)
# Note the equivalence with map
x <- matrix(1:24, ncol=4)
map(t(x), function(a) sum(a)) == fold(x, function(a,b) a + b, 0)
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.