Defining and applying functions in kdb+ is terse, compact and powerful. By applying q idioms we can often write a few lines of code to replace what in other languages would take many pages of code. We'll show you below how to get started writing kdb functions.

Defining and Calling Functions

The body of a function is defined within curly braces {}. THe first square brackets inside the body specify the arguments of the function. Any statements that make up the function then occur separated by either a new line or semi-colon. The value of the last statement within the body is returned from the function.

To specify a function with two arguments we use a semi-colon to separate the named arguments within the function. Notice when calling a function that the syntax is similar to indexing in lists or retrieval from dictionaries.

Anonymous Functions

In the previous example we assigned a function to the variable f. It is in fact not necessary to assign or name a function. The function can be placed inline, this is called an anonymous function.

Implicit Arguments

Although kdb functions are already terse, we can make them even shorter. The q language has the concept of implicit arguments, these are variable names that when used within the body are assumed to be arguments. q permits up to three implicit arguments: x,y,z. When the explicit arguments are not specified (i.e. no square brackets) and the variables x,y,z are used within the function, the function is implicitly assumed to have them as an argument.

To separate sequences of instructions within a function body we can either take a new line or use semi-colons, I recommend always using semi-colons. At this point you may want to switch to an IDE like qStudio that allows sending multi-line commands.

If we want to return a value early we can use a single colon without a left hand argument.

Local/Global Variables and Precedence

Variables declared within a function are local to that function. If a global with the same name exists its value will be read in but to write a value to a global variable we must explicitly use the double semi-colon operator.

Projection

In q we can specify some arguments to a function as constant, to create a new function with fewer arguments, this is called projection. In other languages you may have met a similar concept called currying. It's very useful when you want to create a function that is a specific instance of a more general function.

Functional Form

q supports functions as nouns. Earlier we demonstarted assigning functions to variables using the standard colon assignment operator. We can in fact pass functions around, dynamically changing the actual function called, similar to languages like javascript. This means we now need a verb that says "apply" this function to these arguments, The dot. and at@ operators support this use: