MarkoL
MarkoL

Reputation: 23

How to use map for multiple conditions

is it possible to use map with multiply condition. For example a list [1,-2,3,-4] it should +1 for all <0 and *2 for >0?

Upvotes: 2

Views: 433

Answers (2)

Enlico
Enlico

Reputation: 28500

The following is a bit ugly, but works:

map (\x -> if x < 0 then x+1 else x*2) [1,-2,3,-4,0]

Upvotes: 2

K. A. Buhr
K. A. Buhr

Reputation: 51159

map itself can only apply the same function to each element of the list, but the function can decide how to operate on each element.

For example, if we write a function to double all odd numbers and add 100 to all even numbers:

myFunc x | odd x     = 2 * x
         | otherwise = 100 + x

we can apply that function using map:

> map myFunc [1..4]
[2,102,6,104]

Upvotes: 4

Related Questions