Haskell – Explanations about the mechanics of a simple factorial function

haskell

I'm new to Haskell, so I'm both naive and curious.

There is a definition of a factorial function:

factorial n = product [1..n]

I naively understand this as: make the product of every number between 1 and n. So, why does

factorial 0

return 1 (which is the good result as far as my maths are not too rusted)?

Thank you

Best Answer

That's because of how product is defined, something like:

product []     = 1
product (n:ns) = n * product ns

or equivalently

product = foldr (*) 1

via the important function foldr:

foldr f z []     = z
foldr f z (x:xs) = f x (foldr f z xs)

Read up on folding here. But basically, any recursion must have a base case, and product's base case (on an empty list) clearly has to be 1.

Related Topic