Factorial in Factor

Example for versions Factor 0.94

The first line lists the necessary dictionaries: formatting (printf), kernel (dup), math (arithmetical operators) and sequences (iota).

Next the definition of factorial word follows which replaces an integer n with its factorial on the top of the stack. To do this, it constructs an array of numbers from 0 to n — 1 (word iota) and folds it with 1 using quotation [ 1 + * ] (increment and multiply) and combinator reduce.

The main program constructs a list of numbers from 0 to 16 (iota again) and for each of them (combinator each) applies the quotation which calculates the factorial and outputs the result in required format.

Standard dictionary math.combinatorics contains word factorial defined exactly like this.

USING: formatting kernel math sequences ;
IN: factorial-example

: factorial ( n -- n! )
    iota 1 [ 1 + * ] reduce ;

17 iota
[ dup factorial "%d! = %d\n" printf ] each