I'm going through the Richard Bird's "Thinking Functionally with Haskell" book and there is a section that I can't understand where he's proving a property of the filter method. What he's proving is:
filter p . map f = map f . filter (p . f)
Previously in the book, he defines the filter as:
filter p = concat . map (test p)
test p x = if p x then [x] else []
This is how he proves the first equation:
filter p . map f
= {second definition of filter} -- He's referring to the definition I gave above
concat . map (test p) . map f
= {functor property of map}
concat . map (test p . f)
= {since test p . f = map f . test (p . f)}
concat . map (map f . test (p . f))
= {functor property of map}
concat . map (map f) . map (test (p . f))
= {naturality of concat}
map f . concat . map (test (p . f))
= {second definition of filter}
map f . filter (p . f)
What I can't understand is how test p . f
is equal to map f . test (p . f)
.
This is how I tried to test it:
test :: (a -> Bool) -> a -> [a]
test p x = if p x then [x] else []
test ((<15) . (3*)) 4 -- test p .f, returns [4]
(map (3*) . test((<15) . (3*))) 4 -- map f . test (p . f), returns [12]
Can anyone please explain what I'm missing here?