Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map function if a predicate holds

I feel like this should be fairly obvious, or easy, but I just can't get it. What I want to do is apply a function to a list (using map) but only if a condition is held. Imagine you only wanted to divide the numbers which were even:

map (`div` 2) (even) [1,2,3,4]

And that would give out [1,1,3,2] since only the even numbers would have the function applied to them. Obviously this doesn't work, but is there a way to make this work without having to write a separate function that you can give to map? filter is almost there, except I also want to keep the elements which the condition doesn't hold for, and just not apply the function to them.

like image 891
Paul Avatar asked Feb 12 '11 19:02

Paul


1 Answers

If you don't want to define separate function, then use lambda.

map (\x -> if (even x) then (x `div` 2) else x) [1,2,3,4]

Or instead of a map, list comprehension, bit more readable I think.

[if (even x) then (x `div` 2) else x | x <- [1,2,3,4]]
like image 198
Cat Plus Plus Avatar answered Oct 10 '22 15:10

Cat Plus Plus