I have a list of integers. Also, I have a function which returns True when the element is non-zero, and returns False when the element is zero (let's call it FUNCTION1).

So, how to define another function (using FUNCTION1), which will give us a new list and only include the non-empty elements?

For example, we have [1,2,3,0,6,0], and we want [1,2,3,6]

  • 6
    Programming questions should be asked on stackoverflow.com – Philipp May 10 '13 at 14:27

What you're looking for is the filter function.

To filter out 0 from a list, you would say:

filter (\x -> not (x==0)) [1,2,3,0,6,0]
-- or better yet
filter (not . (==0)) [1,2,3,0,6,0]
-- or best of all
filter (/=0) [1,2,3,0,6,0]

If you want, you can substitute the anonymous function with your named function. It should work the same:

filter Function1 [1,2,3,0,6,0]
| improve this answer | |
  • 6
    I'd like to introduce you to my good friend (/=) ;-) – user7043 May 10 '13 at 14:22
  • 1
    @delnan Why thank you. Pleasure to meet you (/=). I'll add you right into the list. (I barely use Haskell, so bear with me ;p) – KChaloux May 10 '13 at 14:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.