Why does product [] return 1?

Why does the product function in Haskell return 1 if it is given an empty list?

+6
source share
4 answers

Lists form a monoid structure with an associative binary operation ++ and a neutral element [] . That is, we have

 [] ++ xs = xs = xs ++ [] (xs ++ ys) ++ zs = xs ++ (ys ++ zs) 

Meanwhile, the numbers have a lot of monoid structure, but it is important here that where the operation is * , and the neutral element is 1 .

 1 * x = x = x * 1 (x * y) * z = x * (y * z) 

The product function is not only a map from lists of numbers to numbers: it is a monoid homomorphism that reflects the monoid structure of the list in a numerical monoid. Cardinally

 product (xs ++ ys) = product xs * product ys 

and

 product [] = 1 

In fact, in order to get the first, we are largely forced to impose ourselves on the latter.

+17
source

This is a math thing - you usually define an empty amount as 0 and an empty product as 1 because it will fit your usual laws well

for example, in this way, you can justify the inductive definition of a product - see Wikipedia

+7
source

Since this is an identity in the category of multiplication.

To be more practical:

 product [1,2,3] == product [1] * product 2:3:[] == product [1] * product [2] * product 3:[] == product [1] * product [2] * product [3] * product [] 

This, in turn, allows you to implement it with simple recursion:

 product [] = 1 product (x:xs) = x * product xs 
+7
source

The product is a fold with an initial value of 1, so when folding an empty list, it simply returns the value of init, which is 1.

Product implementation example to illustrate it:

 product :: [Int] -> Int product lst = foldr (\xy -> x*y) 1 lst 

Take a look to understand correctly.

+2
source

All Articles