Etch Calculation

If we want to display a function that increments each element of the range by 1, we could write

map (\x -> x + 1) [1..5] 

but I think most people will just go for

 map (+1) [1..5] 

instead of this. But this obviously does not work with (-1), since this one is negative.

So, the first thing that came to mind was

 map (+(-1)) [1..5] 

which will make sense considering how subtraction is defined in Prelude ( x - y = x + negate y ), but it looks a bit strange to me. Then i came up with

 map (flip (-) 1) [1..5] 

It somehow looks better for me, but maybe it is too complicated.

Now I know this doesn't matter, but I wonder if I am missing a more obvious way to write this? If not, which of the two methods would you prefer? I just ask because often these small details like this make your code more idiomatic and therefore enjoyable for other developers who need to read it.

Decision

Now that I have received a couple of answers, I think my personal favorite

 map (subtract 1) [1..5] 

followed by

 map pred [1..5] 

mainly because the first one is really clear, and no one should guess / look for what pred (predecessor) means.

+47
coding-style haskell
Dec 15 '10 at 20:29
source share
4 answers

You can use the subtract function instead of - if you want to subtract to the right:

 map (subtract 1) [1..5] 
+42
Dec 15 '10 at 20:36
source share

Since - is both a subtraction of the infix and a negate prefix, you cannot use the syntax (*x) (where * is the infix operator and x is the value) for - . Fortunately, Prelude comes with negate and subtract , which corresponds to \x -> -x and \xy -> yx respectively, so you can use the ones where you need to distinguish between the two.

+9
Dec 15 '10 at 23:18
source share

I think that map (\x -> x - 1) [1..5] better conveys the intention of the programmer, since there is no doubt that it is subtracted from what. I also found your first solution, map (+(-1)) [1..5] , easy to read.

+2
Dec 15 '10 at
source share

I don't like subtract because it is ridiculously backward. I suggest

 minus :: Num n => n -> n -> n minus = (-) infixl 6 `minus` 

Then you can write

 map (`minus` 1) [1..5] 
+2
Aug 25 '14 at 14:14
source share



All Articles