_fold
Applies a QL expression iteratively to the elements of a List --
Function
Anything -> _fold
(init, exp) -> The same Type
- Receives
- A List of any sort
- init
- The start value
- exp
- An expression to run on each element of the collection
- Produces
- The result of running
exp
over each element of the List
This function is advanced, but sometimes enormously useful. It is Querki's version
of the common functional-programming function fold().
Basically, this receives a List, and takes two parameters: an initial value and
an expression. It runs through the List, one element at a time, building up an
"accumulator". Each time through, you get the current accumulator and the next
element; the expression should result in a new value, which will become the
new accumulator.
The accumulator is passed into the expression as the bound name $acc
; the next
element as $next
.
It is best understood through an example. This is how you would implement "sum"
using _fold
:
<1, 2, 3, 4> -> _fold(0, $acc -> _plus($next))
That is, you can think of a sum as simply adding all of the elements together
one at a time. So you start with 0 (the first parameter). The first time it
calls the expression, $acc
is 0 and $next
is 1 (the first element of the List),
so it results in 1. Next time around, $acc
is 1 and $next
is 2 (the next element),
so it results in 3. Then it adds 3 and 3 to get 6; then it adds 6 and 4, to get 10.
For convenience, the value of $acc
is also given at the context of the expression.
So you could actually express the above even more concisely as:
<1, 2, 3, 4> -> _fold(0, _plus($next))