Next: , Previous: , Up: Top

## 9 User Functions

User-defined functions can be created. As these functions are built on top of the fast internal functions of k9 they should be performant also.

```Func {[a;b]a+b}
```

### 9.1 Function arguments

Functions default to arguments of x, y, and z for the first three parameters but this can be explicitly added or modified as needed. Given k9’s terseness it’s rare to see good k9 code with long variable names.

``` f1:{x+2*y}         / implicit arguements
f1[2;10]
22

f2:{[x;y]x+2*y}    / explicit
f2[2;10]
22

f3:{[g;h]g+2*h}    / explicit and renamed
f3[2;10]
22

f4[2;10]
22

@f1
`.
```

### 9.2 Calling functions

Functions, like lists, can be called with a number of notations. Typically one uses square bracket notation when the function takes multiple argruments. If a function is called with less than the required number of arguments then it will return a function that requires the remaining arguemnts.

``` f1:{[x] x}
f2:{[x;y](x;y)}
f3:{[x;y;z](x;y;z)}

f1[`a]
`a

f2[37;`a]
37
a

f3["hi";37;`a]
hi
37
a

f2
{[x;y](x;y)}
f2[;`a]
{[x;y](x;y)}[;`a]

f1[`a]
`a
f1 `a
`a
f1@`a
`a
```

### 9.3 Anonymous functions

``` {x+2*y}[2;10]
22
```

### 9.4 Recursive functions

``` f:{\$[x>1;x*f@x-1;1]};f 5
120
```

### 9.5 Chained functions

It may be neccesary to define a function to call a function without specifying arguments. Imagine this trivial case.

``` f1:{!x}
f2:{x+2} f1
{x+2}
^
:rank
```

In order to succeed f1 needs to have an `@` in the definition of f2. This is only required when the function calls a function that is not completely specified with input parameters.

``` f1:{!x}
f2:{x+2} f1@
f2 3
2 3 4
```

Next: , Previous: , Up: Top