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.

user6731064
  • 321
  • 1
  • 2
  • 10
  • 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`. – Carcigenicate Jan 02 '17 at 17:30
  • 3
    Downvoter should comment, given neither the answer or question are really that bad. – Carcigenicate Jan 02 '17 at 17:34
  • @Carcigenicate Ah thank you that makes sense – user6731064 Jan 02 '17 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. – amalloy Jan 02 '17 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. – Carcigenicate Jan 02 '17 at 23:40

1 Answers1

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

Simon H
  • 20,332
  • 14
  • 71
  • 128
  • 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. – Alec Jan 02 '17 at 17:33
  • 1
    @Simon H that's great thank you, clearly I need to brush up on composition and application – user6731064 Jan 02 '17 at 17:35
  • Note: you do need to have the `fn` parameter at all: `all = and . map` is fine. – Bakuriu Jan 02 '17 at 17:56
  • @Bakuriu See http://stackoverflow.com/q/16888222/625403 for one of the many questions asking why the thing you propose doesn't work. – amalloy Jan 03 '17 at 00:33