Yes, I can write a simple recursive function in Haskell. Let’s define a function that calculates the factorial of a non-negative integer. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted as n! and is defined as follows:
- ‘0! = 1‘
- ‘n! = n * (n - 1)!‘ for ‘n > 0‘
Here’s the Haskell code for a recursive factorial function:
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)
The factorial function takes an Integer as input and returns an Integer as output. The function covers two cases:
1. The base case, when the input is 0, the function returns 1 (‘0! = 1‘).
2. The recursive case, when the input is n (n > 0), the function returns the product of n and the factorial of n-1 (‘n! = n * (n - 1)!‘).
Let’s take a look at how this function works for the input 4:
factorial 4 = 4 * factorial 3
= 4 * (3 * factorial 2)
= 4 * (3 * (2 * factorial 1))
= 4 * (3 * (2 * (1 * factorial 0)))
= 4 * (3 * (2 * (1 * 1)))
= 4 * (3 * 2)
= 4 * 6
= 24
Thus, the factorial of 4 is 24.