Anonymous Function

An anonymous function is a shorthand function without a name. It can be used in the following ways:

  • assigned to another function as a parameter

  • assigned to a variable for future use

  • serve as the return object of another function

  • for in place call

Syntax

def (parameters){statements}

or

def (parameters): expression

Examples

Assigned to another function as a parameter:

each(def(a,b):a+b, 1..10, 2..11);
// output
[3,5,7,9,11,13,15,17,19,21]
// for more details, please see function each

Assigned to a variable for future use:

g=def(x):2*x;
g(2);
// output
4

Serve as the return object of another function:

def f(x){return def(k): k*x};
f(7)(8);
// output
56

In place call:

def(a,b){return (a+1)*(b+1)} (4,5);
// output
30

Except for user-defined aggregate functions (see Named Function), DolphinDB supports user-defined anonymous aggregate functions. The syntax is basically the same as that of anonymous functions.

f = defg (x){return sum(x)+1};
x = 1..5;
f(x);
// output
16
f = defg (x){return defg(k): sum(k*x)}
x = 1..5
y = 6..10
f(x)(y)
// output
130