Felipe Rabelo
Felipe Rabelo

Reputation: 13

List comprehension and filtering elements

I've been trying to create a comprehension for a, technically, simple case of list, but I'm not sure if Haskell can achieve the result I want the way I expected.

If I wanted to make a list of numbers from 1 to 20, filtering the numbers whom aren't both divisible by 3 and 5 at the same time, this would be as simple as

[x | x <- [1..20], not $ x `mod` 3 == 0 && x `mod` 5 == 0]

Which would result in a list with every number from 1 to 20 without the 15.

But, what if I wanted that instead of excluding the number 15, that position of the list would be filled with a 0? The same applying if the range was bigger and I wanted that every case which my filter is false, instead of not taking the number, it would attribute to x a predetermined value (in my example, 0), can this be achieved with a list comprehension or should I use another solution?

Upvotes: 1

Views: 118

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477686

But, what if I wanted that instead of excluding the number 15, that position of the list would be filled with a 0?

In that case, this is not filtering, but a mapping where you add a condition in the map such that elements that are dividably by 3 and 5 (for this specific case, we can just say dividably by 15), should map to 0:

[ if mod x 3 == 0 && mod x 5 == 0 then 0 else x | x <- [1..20]]

or more compact:

[ if mod x 15 == 0 then 0 else x | x <- [1..20]]

Upvotes: 3

Related Questions