Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing filter using HoF in Haskell

Tags:

list

haskell

I'm trying to write a function that takes a predicate f and a list and returns a list consisting of all items that satisfy f with preserved order. The trick is to do this using only higher order functions (HoF), no recursion, no comprehensions, and of course no filter.

like image 369
dpsthree Avatar asked Sep 03 '10 04:09

dpsthree


People also ask

How does the filter function work in Haskell?

As we know a filter is used to filter or extract the data or elements from the given data structure for use. This filter condition can be anything based on the predicate we apply. Once we apply the predicate it will return us the elements which satisfy the predicate condition.

How does Foldr work in Haskell?

Haskell : foldr. Description: it takes the second argument and the last item of the list and applies the function, then it takes the penultimate item from the end and the result, and so on. See scanr for intermediate results.

What does () mean in Haskell?

() is very often used as the result of something that has no interesting result. For example, an IO action that is supposed to perform some I/O and terminate without producing a result will typically have type IO () .


1 Answers

You can express filter in terms of foldr:

filter p = foldr (\x xs-> if p x then x:xs else xs) []
like image 188
Martijn Avatar answered Oct 17 '22 12:10

Martijn