2

I'm learning Haskell using CIS194(spring13) by myself. Today when I was trying to deal with homework 4 Exercise 1, I got a error with

fun1' :: [Integer] -> Integer
fun1' = foldl' (*) 1 . map (-2) . filter even

It's said:

error:
    ? No instance for (Num (Integer -> Integer))
        arising from a use of syntactic negation
        (maybe you haven't applied a function to enough arguments?)
    ? In the first argument of map, namely (- 2)
      In the first argument of (.), namely map (- 2)
      In the second argument of (.), namely map (- 2) . filter even
   |
12 | fun1' = foldl' (*) 1 . map (- 2) . filter even

   |                             ^^^

And It's OK to replace (-2) with (\x -> x - 2). I think it just like filter (==0) or map (*3) xs, (-2) should be a function with type signature Integer -> Integer and has same effect with (\x -> x - 2).

So my question is why they are different?

SkyBlond
  • 31
  • 2

1 Answers1

8

Haskell has a special case in its syntax for -; it is treated as a unary operator, synonymous with negate, whenever that parses. It was considered at the time the language was made that negative numbers would be more commonly needed than subtraction sections (and this still seems true today).

However, it was known that people would occasionally want what you do, and so provisions were made: the Prelude includes a function named subtract which just flips the arguments to (-).

> map (subtract 2) [1,2,3]
[-1,0,1]
Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380
  • “considered at the time the language was made that negative numbers would be more commonly needed than subtraction sections” – I think they _are_ more commonly needed. Still I think this could have been addressed better in some other way. — Even with the current syntax, `subtract` isn't really _necessary_ – `(-2+)` could be used as well, should be equivalent in practice though it technically speaking uses different ops. `subtract` keeps disgruntling me; I do use it because it's the conventional thing to do, but it feels totally awkward. – leftaroundabout Dec 10 '18 at 12:10
  • @leftaroundabout Ah, I see how my wording could imply that the consideration of the time was wrong. That wasn't intended; let me try to fix it up. And even if `(-2+)` were the idiom instead of `subtract 2`, that wouldn't have prevented this question from being asked... – Daniel Wagner Dec 10 '18 at 12:16