From bc42812715fb56e72717bf18809dd9ba59771b3a Mon Sep 17 00:00:00 2001 From: Stephen Dolan Date: Thu, 16 May 2013 15:07:53 +0100 Subject: Remove the insane "fold" operation, replace with saner "reduce". --- docs/content/3.manual/manual.yml | 34 ++++++++++++---------------------- 1 file changed, 12 insertions(+), 22 deletions(-) (limited to 'docs/content') diff --git a/docs/content/3.manual/manual.yml b/docs/content/3.manual/manual.yml index 7038b5fc..9b8a7b4a 100644 --- a/docs/content/3.manual/manual.yml +++ b/docs/content/3.manual/manual.yml @@ -1016,7 +1016,7 @@ sections: (many jq functions such as `map` and `find` are in fact written in jq). - Finally, jq has a `fold` operation, which is very powerful but a + Finally, jq has a `reduce` operation, which is very powerful but a bit tricky. Again, it's mostly used internally, to define some useful bits of jq's standard library. @@ -1126,36 +1126,26 @@ sections: input: '[[1,2],[10,20]]' output: ['[[1,2,1,2], [10,20,1,2]]'] - - title: Fold + - title: Reduce body: | - The `fold` syntax in jq allows you to combine all of the + The `reduce` syntax in jq allows you to combine all of the results of an expression by accumulating them into a single answer. As an example, we'll pass `[3,2,1]` to this expression: - fold 0 as $sum (.[] | $sum + .) + reduce .[] as $item (0; . + $item) - The variable `$sum` is first given the value `0`. The body - of the fold (i.e. `.[] | $sum + .`) is evaluated. `.[]` - produces three results, `3`, `2`, and `1`. For the first - one, `$sum + .` gives `3`. + For each result that `.[]` produces, `. + $item` is run to + accumulate a running total, starting from 0. In this + example, `.[]` produces the results 3, 2, and 1, so the + effect is similar to running something like this: - Having produced this answer, jq backtracks to find the next - result as per usual. However, this time, `$sum` is set to - the previous value of the body, so `$sum + .` gives - `5`. After the final backtracking, `$sum + .` gives - `6`. This final value is used as the value of the entire - `fold` expression, so the above filter returns `6`. - - More formally, in order to evaluate `fold INIT as $VAR - (BODY)`, jq first sets `$VAR` to the value of `INIT`. It - then runs through `BODY`. Each time `BODY` produces a value, - `$VAR` is set to that value and jq backtracks to find the - next one. When `BODY` stops producing values, the final - value of `$VAR` is the result of the entire expression. + 0 | (3 as $item | . + $item) | + (2 as $item | . + $item) | + (1 as $item | . + $item) examples: - - program: 'fold 0 as $sum (.[] | $sum + .)' + - program: 'reduce .[] as $item (0; . + $item)' input: '[10,2,5,3]' output: ['20'] -- cgit v1.2.3