# The factorial

The factorial of a non-negative integer $n$ , denoted by $n!$ , is the product of all positive integers less than or equal to $n$ :

$n!=n\cdot (n-1)\cdot (n-2)\cdot (n-3)\cdot \ldots \cdot 3\cdot 2\cdot 1.$ For example,

$5!=5\cdot 4\cdot 3\cdot 2\cdot 1=120.$ The value of $0!$ is 1, according to the convention for an empty product.

The factorial operation is encountered in many areas of mathematics, notably in combinatorics, algebra, and mathematical analysis. Its most basic use counts the number of distinct sequences—the permutations—of $n$ distinct objects: there are $n!$ .

# Implementing the factorial in q

We'll implement the factorial as a q function. That function will take a single parameter, x, and return the result.

fact:{[x]1f}


This defines a function, {...}, which takes a single argument, [x], which always (irrespective of the argument) returns 1f. We assign, :, a name to that function, fact, so we can call it again and again, as required.

This is a function of a single argument, in other words, a monadic or unary function. We could have a dyadic (binary), triadic (ternary), etc. function. Here is an example of a dyadic function:

add:{[x;y]x+y}


When q encounters the variables named x, y, and z in the body of a function, it knows that these are the function's arguments. So we could skip [x;y] above:

add:{x+y}


We wouldn't be able to do this if we named the arguments differently:

add:{[a;b]a+b}