cheshire
cheshire

Reputation: 1159

Haskell map function, return a list without zeroes

Here is my code:

x = map classify[1..20] 

classify :: Int -> Int 
classify n 
         | n `mod` 2 == 0 = n + 2
         | otherwise = 0

When calling x it returns a list

[0,4,0,6,0,8,0,10,0,12,0,14,0,16,0,18,0,20,0,22]

How can I specify that I want just numbers that are not 0 is list:

[4,6,8,10,12,14,16,18,20,22]

Upvotes: 2

Views: 801

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477190

You can use a filter :: (a -> Bool) -> [a] -> [a] for this. This function takes a function (of type a -> Bool called the "predicate") and a list, and it generates a list of values where the predicate is satisfied (returns True for that element).

So you can filter out zeros with:

filter (0 /=) mylist

For your sample list, this generates:

Prelude> filter (0 /=) [0,4,0,6,0,8,0,10,0,12,0,14,0,16,0,18,0,20,0,22]
[4,6,8,10,12,14,16,18,20,22]

That being said, for this specific case, you can save yourself the trouble from generating such elements in the first place by making "hops of 2":

x = map classify [2, 4..20]

This thus will map a list that contains [2,4,6,8,10,12,14,16,18,20], all the elements in between will - given your function - be mapped to zero. By making hops of two, we avoid calculating these values in the first place. But this of course only works for this specific case.

Upvotes: 9

Related Questions