Lambda Expression

Lambda expression is a function definition with only one statement.

Syntax

def <functionName>(parameters): expression

or

def (parameters): expression

or

def (parameters) -> expression

or

parameter -> expression

Details

Lambda expression can be either a named function or anonymous function. It takes any number of parameters but has only one expression. The second, third, and fourth of the aforementioned syntax define an anonymous Lambda function and the fourth syntax only applies to a statement with one parameter. An anonymous Lambda function can be used in the following ways.

  1. Assigned to a variable, e.g. f=def(x):x*x.

  2. Used as the parameter to a function, e.g. each(def(a,b):a+b, 1..10, 2..11).

  3. Used as the return value of a function, e.g. def(x){return def(k): k*x}.

  4. Besides the aforementioned usages, Lambda expression can also be wrapped in curly braces {}, which supports:

    • Used as a function with one parameter, e.g. {x->x*x}(10).

    • Used as an operator. The precedence of binary operators is the same as that of multiplication and division, while unary operators have the lowest precedence. For example, the correct precedence of {x->x*x} 10 {x,y->x+y} 1 is to first execute 10 {x,y->x+y} 1, which results in 11, and then apply {x->x*x} to 11 and return the final result 121.

    • Used with symbols of higher-order functions, e.g. {x->x*x + x}:E matrix(1 2 3, 4 5 6).

    • Called by object.method().

Examples

def f(x):x pow 2 + 3*x + 4.0;
f(2);
// output
14

def orderby(x,y): x[isort y];
t=table(3 1 7 as id, 7 4 9 as value);
orderby(t, t.id);
id value
1 4
3 7
7 9
each(def(a,b):a+b, 1..10, 2..11);
// output
[3,5,7,9,11,13,15,17,19,21]

g = def (x,y) -> log(x) + y pow 2;
g(e,0);
// output
1

each(x->x+1,1 3 5)
// output
[2,4,6]

Used as the return value of a function:

def f1(x){return def(k): pow(x,k)}
f1(1)
//output: {def (x, k)->power(x, k)}{1}
f1(1)(10)  
//output: 1

Examples of Lambda expression wrapped in curly braces {}:

  • Used as a function:

    {x->x*x}(2)  
    //output: 4
    
    // Wrap an aggregate function
    {defg(x)-> sum(x)/max(x)}(2 5 6)
    //output: 2
  • Used as an operator:

    {def(x):x*x} 4
    //output: 16
    2 *{x->x*x} 10 {x,y->x+y} 1 
    //output: 242

When used as a unary operator, multiple operators can be used consecutively in a single expression:

{x->x*x}{x->x+1}{x->x*2} 10
//output: 441

Call Lambda expression using object.method().

v = 1..6 
v.{x->x*x+1}() 
// output [2,5,10,17,26,37]

object.method() can also be used with higher-order functions. For example, to apply the Lambda expression on each row of a matrix, you can use object.method() with byRow(:H):

m = matrix(1 2 3, 4 5 6, 7 8 9) 
m.{x->cumavg(x)*x+x}:H()

#0

#1

#2

2 14 35
6 22.5 48
12 33 63