@RebeccaSkinner
On p.61 in Chapter 2, the following is described as finding “the sum of the first ten odd numbers”:
λ (foldr (+) 0 . filter odd) [0..10]
25
In fact, this code sums the odd numbers between 0 and 10 – that is, the first five odd numbers. For the sum of the first ten odd numbers, you’d probably want something like
λ (foldr (+) 0 . map (\x -> 2 * x + 1)) [0..9]
100
You are correct, this is wrongly stated as being the first ten odd numbers rather than the odd numbers from 0 to 10.
It’s actually not a bad example of the differing use cases for map and filter: if the problem is to “sum the odd numbers between m and n,” then filter is perfect; if the problem is to “sum the first n odd numbers,” map is more appropriate.
I’ve only made it to chapter 3 so far, but I’m really enjoying the book!
1 Like