Dynamic function definition in jq

Idea

In functional languages, a function is a value. So, passing or returning a function is merely passing / returning a value. The principle is simple.

But, applying this simple principle might troublesome when we introduce higher-order-functional feature to an existing language.

There is a modest solution; we will introduce one additional type Thunk to the JSON-base type system.

Definitions
  • a thunk is an opaque value that represents a function. a thunk is not a function itself, but a value. You may think of a thunk as a frozen function.
  • the asterisk symbol '*' defrosts a thunk. A thunk is activated by prefixed '*', and it can work as a function
  • the ampersand symbol '&' freezes (i.e. creates thunk from) an actual function. &foo is a value that you can freely pass / return.
Dynamically created thunk

Specification of the function dyn_def :

  • dyn_def(params: string, body: string) : IGNORE -> Thunk
  • params : a string that is, when parsed, syntactically valid function parameter declaration.
  • body : a string that is, when parsed, syntactically valid function body.
  • dyn_def ignores her input.
  • dyn_def returns a thunk -- the value which represents a defined function.
10 | dyn_def("(a, b)", "a * . + b") as $linear_function | *$linear_function(2, 5)
# => 2 * 10 + 5 = 25