Description
(Github doesn't support moving PRs from one repo to another, so I've copy-pasted the text of @emanuele6 's PR from the deleted prior jqlang/jq
repository below. The relevant branch is emanuele6:niceadd )
@emanuele6 says:
And reimplement add/0
in terms of those.
Also add documentation.
The add/2
version may appear redundant since it is mostly equivalent to add($initial, generator)
, but it is not really because initial is a $
-argument, so add/2
will output a result for each of the outputs of the first expression; consider the following examples:
$ echo 1 2 | jq --jsonarg -n 'add(inputs; $ARGS.positional[])' -- 3 4
8
9
$ echo 1 2 | jq --jsonarg -n 'add(inputs, $ARGS.positional[])' -- 3 4
10
$
$ jq -n '[] | add(.[], 1)'
1
$ jq -n '[] | add(.[]; 1)'
$ # nothing
If this gets merged, the implementation of walk/1
can be fixed using the fix proposed in #2584.
I think these functions should definitely be builtins since they are very useful to have, it makes sense to have them since they are just a generalisation of the existing add/0
.
Also I had to write manual reduce
loops almost every day when solving last year's advent of code puzzles in jq because add/0
was too unnecessarily slow/heavy for the large inputs, which felt a bit lame. :/
{min,max}/{1,2}
(and maybe also {min,max}_by/{2,3}
) should also be added since those would be useful too, but since the implementation of min/0
and max/0
implementation seems to be written in C, I will leave removing and rewriting the C implementation in jq in terms of max/2
and min/2
to another PR.