Factorial in FP

Example for versions Interactive FP

This example defines four functions — two of necessity, and two for readability. All of them accept scalar values for input; seq returns a sequence of scalars, and the other three return individual scalars.

  • zero checks whether its argument is equal to zero;
  • dec decrements its argument;
  • seq returns <0> if its argument x is equal to zero, and seq, applied to (x-1), with x appended to right otherwise (if we unwind this recursive definition, we’ll get simply the sequence of values <0 1 ... x>).
  • factorial returns 1 if its argument x is equal to zero, and factorial, applied to (x-1), multiplied by x otherwise.

The last line of the example applies factorial to each element of sequence, obtained by applying seq to 16. Note that all math operations produce floating point values, so the actual output will look like this:
< 1 1.0 2.0 6.0 24.0 120.0 720.0 5040.0 40320.0 362880.0 3628800.0 3.99168E7 4.790016E8 6.2270208E9 8.7178289E10 1.30767428E12 2.09227885E13 >

{ zero ( = @ [id, %0] ) }
{ dec ( - @ [id, %1] ) }
{ seq ( zero -> %<0> ; apndr @ [ seq @ dec , id ] ) }
{ factorial ( zero -> %1 ; * @ [id, factorial @ dec ] ) }
&factorial @ seq:16