Trusted answers to developer questions

Ravi

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`

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)

- 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.

`product`

functionThe ** 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.

-- 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)

RELATED TAGS

haskell

CONTRIBUTOR

Ravi

RELATED COURSES

View all Courses

Keep Exploring

Related Courses