Function

Functions are self-contained modules of codes that accomplish specific tasks. Functions include built-in functions and user-defined functions.

Define a Function

To define a function, use keyword "def" before the function name. For details, please refer to Functional Programming. Both built-in functions and user-defined functions support specifying default parameter values. Note that the parameter with a default value cannot be mutable, and the default value must be a constant. All parameters after a parameter that is configured with a default value must also be configured with default values as well.

Note: When using mutable for a parameter in an outer function, all nested functions within it using the same parameter must also be decorated with mutable. Otherwise an error may occur during multi-threaded processing: Read only object can't be applied to mutable function xxx.

def f(a):a*a;
f(5);
// output: 25

def f(a=1, b=2){return a + b}
f(b=3, a=2)
// output: 5

f(,3)
// output: 4

Call a Function

All function parameters are passed by reference. All parameters by default are immutable unless explicitly declared otherwise.

Usually the syntax of a function can take the following 3 forms:

  • standard function call format: <func>(parameters)

  • object-method call format: x.<func>(parameters) where x is the first parameter

  • if there is only one parameter inside the parentheses, we can also use <func> parameter, or x.<func>()

Note: When calling a function with multiple parameters, all arguments passed after a keyword-based argument must be specified in keyword form as well.

Examples

x=1..10;
sum(x);
// output: 55

x.sum();
// output: 55

sum x;
// output: 55

x=2;
y=3;
add(x,y);
// output: 5

x.add(y);
// output: 5

x add y;
// output: 5

By default, parameters are immutable.

x=1..10;
add(x,1);
// output: [2,3,4,5,6,7,8,9,10,11]

x;
// output: [1,2,3,4,5,6,7,8,9,10]

def f(x){x+=1 return x};
// Syntax Error: [line #1] Constant variable [x] can't be modified.

Use "mutable" to declare mutable parameters:

x=1..10;
def f(mutable x){x+=1 return x};
f(x);
x;
// output: [2,3,4,5,6,7,8,9,10,11]        
// note that the values of vector x has been modified

DolphinDB offers almost 1000 built-in functions such as avg, sum, log, add, sub, prod.

avg(1.5 2.5 2 2);
// output: 2

log(10);
// output: 2.302585

prod(1 2 3)
// output: 6