Factorial in Factor

Example for versions Factor 0.94

This example uses a purely recursive approach to factorial calculation. Word factorial replaces n with n! on the stack with a side effect: it prints all values of factorial from 0 to n. After if combinator is applied, the stack holds values of n and n!. Words swap and over replace them with n!, n and n!; two latter values are used for printing, and the first one stays on the stack as a return value.

In the main part of the program we need to add drop to remove 16! from the stack, so that the effect of the program on the stack is ( -- ).

USING: formatting kernel math ;
IN: factorial-example

: factorial ( n -- n! )
    dup
    0 =
    [ 1 ]
    [ dup dup 1 - factorial * ]
    if
    swap over "%d! = %d\n" printf ;

16 factorial
drop