Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elegant way to subtract a number of every list element [duplicate]

Tags:

haskell

I recently ran into following problem: Given a list of numbers, I want to subtract a constant from every entry of this list. The natural but wrong thing to do is

map (-3) [5,6,7]

Here the - is not interpreted a binary function but as an unary negation operator.

I found following workarounds:

map (+(-3)) [5,6,7]
map ((+)(-3)) [5,6,7]
map (flip (-) 3) [5,6,7]

Question : Is there a more elegant way to do this that avoids this unnecessary pile of parenthesis?

like image 955
flawr Avatar asked Jan 25 '26 16:01

flawr


1 Answers

Nope, sorry. You have the subtract function, but it's not shorter.

Prelude> map (subtract 3) [3,4,5]
[0,1,2]
like image 98
Filip Haglund Avatar answered Jan 28 '26 07:01

Filip Haglund



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!