3

Here is the type signature and the definition of the filter function from Learn You a Haskell for Great Good!:

filter' :: (a -> Bool) -> [a] -> [a]
filter' _ [] = []
filter' p (x:xs)
    | p x = x : filter' p xs
    | otherwise = filter' p xs

An usage example in the book is with elem is as follows:

filter' (`elem` ['a'..'z']) "Hell0!"

Which returns:

"ell"

In this particular example, is there a possible way of using elem as a prefix function instead of an infix function as a predicate?

In a more general sense, is there a way to supply only the second parameter in order to partially apply a prefix function?

Thanks in advance for your help!

Ghost Bunnies
  • 177
  • 1
  • 1
  • 8

2 Answers2

5

Either by creating a lambda (which will work for functions taking more than 2 parameters):

filter' (\a -> elem a ['a'..'z']) "Hell0!"

Or by using flip:

filter' (flip elem ['a'..'z']) "Hell0!"
dfeuer
  • 48,079
  • 5
  • 63
  • 167
Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
  • 1
    Worth mentioning: the result is the same for all: `(\`elem\` v)`, `(\a -> elem a v)`, and `(flip elem v)`. Also, if I am not mistaken, you don't need the dollar sign. – jakubdaniel Oct 07 '15 at 14:22
  • @jd823592 I thought a point of it was to provide an equivalent solution, and so I didn't think that mentioning it was important. As for the dollar, I typically leave it for consistency and easier "function" and "data" separation, though I do realize it's very subjective. – Bartek Banachewicz Oct 07 '15 at 14:23
  • 1
    I did not mean to suggest I disapproved. I totally agree with your answer, I just thought it might not be obvious and additional info may improve understanding of the matter. – jakubdaniel Oct 07 '15 at 14:33
  • @bartek-banachewicz, this is what I was looking for, thanks a lot for your help! – Ghost Bunnies Oct 07 '15 at 14:33
1

Sounds like you're after flip :: (a -> b -> c) -> b -> a -> c, which is in the prelude.

It can be implemented as flip f = \b a -> f a b.

chi
  • 111,837
  • 3
  • 133
  • 218
C. Quilley
  • 989
  • 7
  • 7
  • @c-quilley, thanks a lot for your answer, even though I've chosen @bartek-banachewicz's proposition as the best solution, because it suggests two different paths, `flip` is indeed what I was looking for! – Ghost Bunnies Oct 07 '15 at 14:32