2

What was wrong with the following code?

map (+1) [1, 2, 3 ] ==  map (\x -> x + 1) [1, 2, 3]
map (1+) [1, 2, 3] == map (\x -> 1 + x) [1, 2, 3]
map (-1) [1, 2, 3]  == map (\x -> x - 1) [1, 2, 3]
map (1-) [1, 2, 3] == map (\x -> 1 - x) [1, 2, 3]

Why the following does not work?

map (-1) [1, 2, 3]
1234
  • 539
  • 3
  • 12
  • 2
    because `(-1)` is a strange edge case in Haskell. (One of very very very few!) It is constrained to mean the number "negative 1", not a section of the `-` operator. Use the `subtract` function instead if you need this. – Robin Zigmond Aug 29 '21 at 21:53
  • 1
    The error message could probably be clearer, but it suggests that `(-1)` does not have the type `Num a => a -> a` that you might expect it to have. – chepner Aug 29 '21 at 22:19
  • Also see the [`LexicalNegation`](https://downloads.haskell.org/ghc/latest/docs/html/users_guide/exts/lexical_negation.html?highlight=lexicalnegation#extension-LexicalNegation) extension of GHC 9 which would allow the section `(- 1)`, with separating whitespace. – chi Aug 30 '21 at 10:42

1 Answers1

3

(-1) is interpreted as a number: minus one. You can use subtract :: Num a => a -> a -> a to subtract a value:

map (subtract 1) [1, 2, 3]  == map (\x -> x - 1) [1, 2, 3]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555