Navigation
Synopsis Compute the factorial function.
Examples The factorial of a number N is defined as N * (N-1) * (N-2) * ... * 1. Here is the Rascal version:
module demo::basic::Factorial

public int fac(int N) = N <= 0 ? 1 : N * fac(N - 1); 

public int fac2(0) = 1; 
public default int fac2(int N) = N * fac2(N - 1); 

public int fac3(int N)  { 
  if (N == 0) 
    return 1;
  return N * fac3(N - 1);
}
Implementation uses a conditional expression to distinguish cases and here is how to use it:
rascal>import demo::basic::Factorial;
ok
rascal>fac(47);
int: 258623241511168180642964355153611979969197632389120000000000
Indeed, Rascal has arbitrary length integers.

Definitions and do the same using pattern dispatch (Rascal:Function):
rascal>import demo::basic::Factorial;
ok
rascal>fac2(47);
int: 258623241511168180642964355153611979969197632389120000000000
Definition is a more imperative implementation of factorial.
Is this page unclear, or have you spotted an error? Please add a comment below and help us to improve it. For all other questions and remarks, visit ask.rascal-mpl.org.