WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Haskell · Basic · question 20 of 100

Can you write a simple recursive function in Haskell?

📕 Buy this interview preparation book: 100 Haskell questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Haskell interview — then scores it.
📞 Practice Haskell — free 15 min
📕 Buy this interview preparation book: 100 Haskell questions & answers — PDF + EPUB for $5

All 100 Haskell questions · All topics