Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

builtins: Add lazy generator versions of add/0: add/1 and add/2 #2595

Open
stedolan opened this issue May 28, 2023 · 0 comments
Open

builtins: Add lazy generator versions of add/0: add/1 and add/2 #2595

stedolan opened this issue May 28, 2023 · 0 comments

Comments

@stedolan
Copy link
Contributor

(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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants