Next: Expression Evaluation, Previous: Dictionary, Up: k9: Manual

User-defined functions are treated as verbs in k9, so can benefit from the adverbs.

Multi-line functions must be defined with an initial space on all lines except the first. These can be loaded into memory by using the \l command and then used by calling by name.

Func {[a;b]a+b}

- Function arguments
- Function Defitions
- Function Return
- Calling functions
- Anonymous functions
- Recursive functions
- Chained functions

Functions default to arguments of x, y, and z for the first three parameters but one can explicitly spell out these or other argument names. Given k9’s terseness, many k9 programmers prefer short variable names. But this is a matter of taste.

f1:{x+2*y} / implicit arguments x and y f1[2;10] 22 f2:{[x;y]x+2*y} / explicit f2[2;10] 22 f3:{[g;h]g+2*h} / explicit arguments other than x and y f3[2;10] 22 f4:{[please;dont]please+2*dont} / longer argument names are possible f4[2;10] 22 @f1 `.

Functions can have intermediate calcuations and local variables. Function local variables do not affect the values of global variables.

a:3;a 3 f:{a:12;x:sqrt x;x+a} f 10 15.16228 a 3

Function return the last value in the definition unless the definition ends with a semicolon in which case the function returns nothing.

f:{x+2;};f 10 / returns nothing because of final semi-colon f:{x+2;27};f 10 / returns the last value which is 27 27 f:{x+2};f 10 12

Functions, like lists, can be called in a variety of ways. Typically one uses square bracket notation when the function takes multiple argruments. If a function is called with fewer 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[37] {[x;y](x;y)}[37] f2[;`a] {[x;y](x;y)}[;`a] f1[`a] `a f1 `a `a f1@`a `a

It’s possible to define a function without naming it. If the function is to be used in just one place, this can make sense.

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

k9 allows one to define a function which calls itself. Care should be taken to avoid an infinite loop.

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

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

fa:{!x} fb:{x+2} fa {x+2} ^ :rank

In order to succeed fa needs to have an `@`

in the definition of fb. This is required because fb calls fa without specifying an argument for fa. So the argument for fb becomes the argument for fa so the net effect is 2 + !3.

fa:{!x} fb:{x+2} fa@ fb 3 2 3 4

Next: Expression Evaluation, Previous: Dictionary, Up: k9: Manual