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]

closed as off topic by user40980, JeffO, Joris Timmermans, user7043, Bart van Ingen Schenau May 10 '13 at 15:49

Questions on Software Engineering Stack Exchange are expected to relate to software engineering within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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]
  • 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.