0

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.

5
  • 1
    Your last error is because [xs] will only match a list with a single element. Just remove the square braces from the parameter and the argument to map. Commented Jan 2, 2017 at 17:30
  • 3
    Downvoter should comment, given neither the answer or question are really that bad. Commented Jan 2, 2017 at 17:34
  • @Carcigenicate Ah thank you that makes sense Commented Jan 2, 2017 at 17:36
  • @Carcigenicate I don't think this question deserves a downvote either, but that's not my call to make, or yours. People can vote how they like, and there's no obligation to explain why in the comments. Commented Jan 2, 2017 at 23:07
  • @amalloy It's good etiquette to explain a downvote though; especially when the OP only has only 8 rep and may be unaware of something wrong they did. Not necessary, no, but certainly helpful to people who aren't familiar with the site. Commented Jan 2, 2017 at 23:40

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Didn't down vote, but I reckon the person who did would've wanted you to explain the Non-exhaustive patterns in function all error.
@Simon H that's great thank you, clearly I need to brush up on composition and application
Note: you do need to have the fn parameter at all: all = and . map is fine.
@Bakuriu See stackoverflow.com/q/16888222/625403 for one of the many questions asking why the thing you propose doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.