2
class R r where
    sum_ :: Integer -> r
instance R Integer where
    sum_ x = x
instance (Integral a, R r) => R (a -> r) where
    sum_ x = \y -> sum (x + toIngeter y)

The code above is used to sum a sequence of numbers and it can accept variable number of arguments. It runs correctly.

However, if I change the second instance to this:

instance (R r) => R (Integer -> r) where
    sum_ x = \y -> sum (x + y)

and enable FlexibleInstances (otherwise a compile error will be raised in ghc 7.10.2), the function cannot run for multiple parameters.

For example, if I run

sum_ 1 2

an error would be raised:

Non type-variable argument in the constraint: R (a -> t)

But if I add an explicit type signature to parameters it runs correctly:

sum_ 1 (2::Integer)

Why couldn't 2 match the type Integer?

JHobern
  • 866
  • 1
  • 13
  • 20
w0mTea
  • 63
  • 6
  • 1
    Because `2` is a polymorphic literal. It is syntactic sugar for the expression `fromInteger (2::Integer)` which means that `2` could be a value of any Num class. – ErikR Oct 26 '15 at 06:21
  • I think your question is essentially a duplicate of another that was asked just a few hours ago. See in particular [@chi's answer](http://stackoverflow.com/a/33334388/1088108). – Ørjan Johansen Oct 26 '15 at 06:24
  • On the other hand, your question made me aware that one of my comments over at the other question was a bit misguided. – Ørjan Johansen Oct 26 '15 at 06:31

0 Answers0