Search code examples
haskellrecursionfold

What does f [] = v mean in the Foldr Recursion Pattern?


When using the Foldr pattern of recursion for the function product, we get:

product [] = 1
product (x:xs) = x * product xs

My question is, what does the 'product [] = 1' mean? For the sum function for instance, we have sum[] = 0? Is this some sort of limit to the answer?

Thank you in advance.


Solution

  • product [] is the base case. It is easy to see why it exists by working through an evaluation of the function.

    product [5, 4, 8]
    5 * product [4, 8]
    5 * 4 * product [8]
    5 * 4 * 8 * product []
    5 * 4 * 8 * 1
    160
    

    If the base case did not exist, product [] would not be able to evaluate to anything. 1 is the identity for multiplication, just as 0 is the identity for addition, i.e. 1 times any number is always that number, just as 0 plus any number is that number.