Skip to main content

Factorial

rascal-0.40.17

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:

@synopsis{fac1 demonstrates the ternary conditional and recursion}
int fac1(int n) = n <= 0 ? 1 : n * fac1(n - 1);

@synopsis{fac2 demonstrates overloading and dynamic dispatch with pattern matching}
int fac2(0) = 1;
default int fac2(int n) = n * fac2(n - 1);

@synopsis{fac3 demonstrates structured programming and recursion}
int fac3(int n) {
if (n == 0)
return 1;
return n * fac3(n - 1);
}
  • fac1 is defined using a conditional expression to distinguish cases.
  • fac2 distinguishes cases using pattern-based dispatch (Rascal Functions). Here the case for 0 is defined.
  • ❸ Here all other cases for fac2 are defined (as indicated by the default keyword).
  • fac3 shows a more imperative implementation of factorial.

Here is how to use fac:

rascal>fac1(47);
int: 258623241511168180642964355153611979969197632389120000000000

NOTE: Indeed, Rascal supports arbitrary length numbers.

Here is an example of fac2:

rascal>fac2(47);
int: 258623241511168180642964355153611979969197632389120000000000

Benefits

  • This simple demo shows how (recursive) Rascal functions work in three different ways.

Pitfalls

  • Typically writing recursive functions can be avoided using Visit and Descendant, so this example isn't very exemplary of typical Rascal code.