Haskell Language Factorial


The factorial function is a Haskell "Hello World!" (and for functional programming generally) in the sense that it succinctly demonstrates basic principles of the language.

Variation 1

fac :: (Integral a) => a -> a
fac n = product [1..n]

Live demo

  • Integral is the class of integral number types. Examples include Int and Integer.
  • (Integral a) => places a constraint on the type a to be in said class
  • fac :: a -> a says that fac is a function that takes an a and returns an a
  • product is a function that accumulates all numbers in a list by multiplying them together.
  • [1..n] is special notation which desugars to enumFromTo 1 n, and is the range of numbers 1 ≤ x ≤ n.

Variation 2

fac :: (Integral a) => a -> a
fac 0 = 1
fac n = n * fac (n - 1)

Live demo

This variation uses pattern matching to split the function definition into separate cases. The first definition is invoked if the argument is 0 (sometimes called the stop condition) and the second definition otherwise (the order of definitions is significant). It also exemplifies recursion as fac refers to itself.

It is worth noting that, due to rewrite rules, both versions of fac will compile to identical machine code when using GHC with optimizations activated. So, in terms of efficiency, the two would be equivalent.