Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell map function, return a list without zeroes

Tags:

haskell

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]
like image 624
cheshire Avatar asked Dec 07 '25 04:12

cheshire


1 Answers

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.

like image 59
Willem Van Onsem Avatar answered Dec 08 '25 21:12

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!