How to use curried functions in Haskell with map?

450 views Asked by At

Trying to learn how to use folds by redefining prelude functions:

import Prelude hiding (sum, product, length, and, or, all, any, filter)

So far I've got up to all working, but I can't figure out what I'm doing wrong with all. I'm defining it as follows:

and :: [Bool] -> Bool
and = foldr (&&) True

...

all :: (a -> Bool) -> [a] -> Bool
all = and $ map

But this displays an error saying :

Probable cause: ‘map’ is applied to too few arguments

I've also tried defining it as:

and :: [Bool] -> Bool
and = foldr (&&) True

...

all :: (a -> Bool) -> [a] -> Bool
all f [xs] = and $ map f [xs]

This compiles fine, but when I try to call it it says:

[1 of 1] Compiling Fold             ( Fold.hs, interpreted )
Ok, modules loaded: Fold.
*Fold> all even [0,2,4,6]
*** Exception: Fold.hs:17:1-29: Non-exhaustive patterns in function all

which I don't understand since shouldn't [xs] match any list, even an empty one? Why can I curry foldr without including the list but not map? Any help would be appreciated.

1

There are 1 answers

4
Simon H On BEST ANSWER

You mixed up function application with composition. Does this help?

all :: (a -> Bool) -> [a] -> Bool
all fn = and . (map fn)

In practise, this is equivalent to your code + the comment from @Carcigenicate