Skip to content

Add a higher-order "flip" function to allow swapping function input/arguments #3443

@infinity0

Description

@infinity0

jq has several "inverse" function-pairs such as in/has and inside/contains, where the input and argument are reversed. However defining pairs like this for every single function is not scalable; and currently one has to do a lot of manual variable binding which gets tedious.

It would be good to supply a higher order function flip where . | flip(f, $a, [..]) means the same as . as $orig | $a | f($orig, [..]).

Real world example:

$ ip -j -6 addr show primary scope global | jq -r '
        .[] .addr_info[] .local //empty 
        |select(. as $i |any("fd", "fc"; . as $p |$i |startswith($p)) |not)'
2001:blah blah blah

would be cleaner written as

$ ip -j -6 addr show primary scope global | jq -r '
        .[] .addr_info[] .local //empty 
        |select(. as $i |any("fd", "fc"; flip(startswith, $i) |not)'
2001:blah blah blah

(Yes, in this specific example I could just use regex, but I'm sure there are lots of other possible cases where such a concise alternative isn't available.)

Broadly speaking, flip is quite a core concept in FP language theory, and is implemented in core libraries of all major FP languages including Haskell, Ocaml, etc, etc. Since jq is heavily inspired by these concepts, it would be fitting to add flip.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions