# Tutorials/Functions

*Prerequisites: The Basics, Datatypes, Lists.*

# Functions

Functions are useful when you want to reuse a block of code. Some functions are built into q – we have already seen `first`

and `last`

. Here are some more examples:

q)til 5 0 1 2 3 4 q)sum 1 5 7 34 47

As you can see, each function has input (known as *parameters*) and an output (*result*). You can also define your own functions. Have a look at the following example and see if you can figure out what’s happening.

q)f:{prd 1 + til x} q)f 3 6

q will recognize up to three implicit parameters (`x`

, `y`

and `z`

), but you can explicitly declare up to eight parameter names.
Notice the square bracket/semicolon syntax used for passing in multiple inputs and slao for declaring parameters.

q){y*x+z}[1;2;3] 8 q){[a;b]b+a*a}[3;5] 14

*Tip: Inputs can be of any type: atoms, lists, dictionaries, tables, even functions!*

You might wish to create an intermediate variable in your function. This is called a *local* variable, and is defined only while the function is running.

q)myfunc:{temp:x+y; temp*x*y} q)myfunc[1;2] 6 q)temp 'temp

Notice that the statements within the function are separated by a semicolon.

*Tip: To define a global variable within a function, use a double colon ::.*

Check out some more of q’s inbuilt functions on the reference page, and read more about defining your own functions in Q for Mortals.

*Note: In a q script, when defining functions that span multiple lines, all subsequent lines must be indented.*

# Exercises

1. Use the factorial function f above to evaluate (10!)/(6! × 4!).

2. Write your own function, which takes the parameters n, k to calculate (n!)/(k! × (n-k)!).

3. Write a function without any inputs at all!

*Tip: To execute your function, simply pass in empty square brackets: f[]*

4. Write a function which returns all of the even numbers up to the input. e.g.

q)evens 7 2 4 6 q)evens 8 2 4 6 8