Fold Operators - compose a binary operator
|
Calling Sequence
|
|
foldl(rator, id, r1,r2, ...)
foldr(rator, id, r1, r2, ...)
|
|
Parameters
|
|
rator
|
-
|
operator to apply
|
id
|
-
|
identity or initial value
|
r1, r2, ...
|
-
|
(optional) operands for the call
|
|
|
|
|
Description
|
|
•
|
The left-fold operator foldl composes a binary operator rator, with identity or initial value id onto its arguments r1,r2,... (which may be zero in number), associating from the left. For example, given three arguments a, b, and c, and initial value id, .
|
•
|
The right-fold operator foldr is similar but associates operands from the right. For example, .
|
•
|
More formally, the left-fold operator foldl is defined recursively by and for a positive integer n.
|
•
|
Similarly, the right-fold operator foldr is defined recursively by and for a positive integer n.
|
•
|
When the operator rator being folded is an associative binary operator, both the left-fold and right-fold operators produce the same result. However, foldl is more efficient than foldr.
|
•
|
The fold operators are useful for implementing operations of variable arity in terms of binary operations. See the and example in the Examples section.
|
|
|
Examples
|
|
>
|
|
| (1) |
>
|
|
| (2) |
>
|
|
| (3) |
>
|
|
| (4) |
Define a dot product as follows.
>
|
|
>
|
|
| (5) |
>
|
|
>
|
|
| (6) |
>
|
|
| (7) |
Although it is not implemented this way, the left-fold operator can be written as one line in Maple.
>
|
|
>
|
|
| (8) |
A typical use of the fold operators is in the implementation of n-ary variants of binary operators. The and operator in Maple accepts only two arguments. A version that accepts any number of arguments can be implemented by using a fold operator as follows. Note that it does not matter which one is used, given that and is associative.
>
|
|
| (9) |
>
|
|
| (10) |
>
|
|
| (11) |
>
|
|
| (12) |
>
|
|
| (13) |
Compute horner forms using foldl.
>
|
|
| (14) |
>
|
|
| (15) |
Count the number of elements of a list.
>
|
|
| (16) |
>
|
|
| (17) |
Reverse a list. Note that this is not the fastest method.
>
|
|
| (18) |
>
|
|
| (19) |
By generating lists, you can compute more than one quantity at a time.
>
|
|
| (20) |
>
|
|
| (21) |
The following example demonstrates an efficient way to test whether a particular predicate returns true for some member of a set or list. The example uses careful sequencing of automatic simplifications and Maple's evaluation rules (which include McCarthy rules for the evaluation of the Boolean operators and and or) to ensure that the procedure returns as early as possible.
>
|
my_ormap := proc( pred::procedure, L::{list,set} )
option inline;
eval(foldl( '`or`', false, op( map( ''pred'', L ) ) ))
end proc:
|
>
|
p := proc(n) print( n ); isprime( n ) end proc:
|
>
|
|
| (22) |
|
|
References
|
|
|
Hutton, Graham. "A tutorial on the universality and expressiveness of fold." J. Functional Programming, Vol. 1(1). (January 1993): 1-17.
|
|
|