If there’s a number n
, find the factorial of n
.
Example 1:
n
=5
120
Example 2:
n
=7
5040
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)
fact
, that takes n
and recursively calculates the factorial of n
.fact
function with 5
as the argument.product
functionThe product
function in Haskell multiplies all the elements in a given list.
The steps are as follows:
1
to n
.product
function to multiply all the numbers in the list.-- 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)