# 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 Chapter 7: 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.

```\$ def f(a):a*a;
\$ f(5);
25

\$ def f(a=1, b=2){return a + b}
\$ f(b=3, a=2)
5

\$ f(,3)
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);
55
\$ x.sum();
55
\$ sum x;
55

\$ x=2;
\$ y=3;
5
5
5
```

By default, parameters are immutable.

```\$ x=1..10;
[2,3,4,5,6,7,8,9,10,11]
\$ x;
[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;
[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);
2

\$ log(10);
2.302585

\$ prod(1 2 3)
6
```