How to find the factorial of a number in Haskell

Problem statement

If there’s a number n, find the factorial of n.

Example 1:

  • Input: n=5
  • Output: 120

Example 2:

  • Input: n=7
  • Output: 5040

Solution 1: Recursion

In this solution, we use the following recursive expression to calculate the factorial of n:

fact(n) = n * fact(n-1)

The code implementation is as follows:

fact n = if n == 0 then 1 else n * fact(n-1)
main = print (fact 5)

Explanation

  • Line 1: We define a function, fact, that takes n and recursively calculates the factorial of n.
  • Line 2: We invoke the fact function with 5 as the argument.

Solution 2: The product function

The product function in Haskell multiplies all the elements in a given list.

The steps are as follows:

  • Generate the list of numbers from 1 to n.
  • Use the product function to multiply all the numbers in the list.

Code

-- Generating the list of numbers from 1 to n
-- and calling the product function to multiply all the numbers in the list.
fact n = product [1..n]
main = print (fact 5)

Free Resources