If we want to map a function that increases every element of a range by 1, we could write
map (\x -> x + 1) [1..5]
but I guess most people would just go for
map (+1) [1..5]
instead. But this obviously doesn't work with (-1) since that's negative one.
So the first thing that came to mind was
map (+(-1)) [1..5]
which would make sense considering how subtraction is defined in the Prelude (x - y = x + negate y
), but looks a bit odd to me. I then I came up with
map (flip (-) 1) [1..5]
This somehow looks better to me, but is maybe a bit too complicated.
Now I know this no big deal, but I'm wondering if I'm missing a more obvious way to write this? If not, which of the 2 ways would you prefer? I'm really just asking because often it's small details like this that make your code more idiomatic and hence pleasant for other developers who have to read it.
Solution
Now that I got a couple of answers, I think my personal favorite is
map (subtract 1) [1..5]
followed by
map pred [1..5]
mostly because the first one is really explicit and nobody needs to guess/look up what pred
means (predecessor).
(-) 1
is a (syntactically valid) way to partially apply the curried-
function. – Deermap ((-) 1) [1..5]
doesn't work, hence the version with flip. – Sandasandakanmap pred
– Gaekwar