Difference between revisions of "Programming/Kdb/Factorial"

From Thalesians Wiki
(Created page with "=The factorial= The factorial of a non-negative integer <math>n</math>, denoted by <math>n!</math>, is the product of all positive integers less than or equal to <math>n</mat...")
 
Line 24: Line 24:
</pre>
</pre>
This defines a function, <tt>{...}</tt>, which takes a single argument, <tt>[x]</tt>, which always (irrespective of the argument) returns <tt>1f</tt>. We assign, <tt>:</tt>, a name to that function, <tt>fact</tt>, so we can call it again and again, as required.
This defines a function, <tt>{...}</tt>, which takes a single argument, <tt>[x]</tt>, which always (irrespective of the argument) returns <tt>1f</tt>. We assign, <tt>:</tt>, a name to that function, <tt>fact</tt>, 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:
<pre>
add:{[x;y]x+y}
</pre>
When q encounters the variables named <tt>x</tt>, <tt>y</tt>, and <tt>z</tt> in the body of a function, it knows that these are the function's arguments. So we could skip <tt>[x;y]</tt> above:
<pre>
add:{x+y}
</pre>
We wouldn't be able to do this if we named the arguments differently:
<pre>
add:{[a;b]a+b}
</pre>

Revision as of 12:01, 30 June 2021

The factorial

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

For example,

The value of 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 distinct objects: there are .

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.

We'll start with a dummy, incorrect implementation that always returns 1:

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}