It turns out that in GHC 7.10, this compiles fine:
mysum xs = foldr (+) 0 xs
But this:
mysum = foldr (+) 0
results in the following error:
No instance for (Foldable t0) arising from a use of ‘foldr’
The type variable ‘t0’ is ambiguous
Relevant bindings include
mysum :: t0 Integer -> Integer (bound at src/Main.hs:37:1)
Note: there are several potential instances:
instance Foldable (Either a) -- Defined in ‘Data.Foldable’
instance Foldable Data.Functor.Identity.Identity
-- Defined in ‘Data.Functor.Identity’
instance Foldable Data.Proxy.Proxy -- Defined in ‘Data.Foldable’
...plus five others
In the expression: foldr (+) 0
In an equation for ‘mysum’: mysum = foldr (+) 0
Why does this happen, and what is the insight that's achieved by understanding this difference? Also, can I give this function a type (that's still generic) to make this error go away?
As usual with cases where making a well-typed function point-free suddenly results in type errors about unfulfilled typeclass constraints, the ultimate cause of this is the monomorphism restriction, enabled by default.
You can solve this by either adding a type signature to mysum
:
mysum :: (Foldable f, Num a) => f a -> a
or by turning off the monomorphism restriction:
{-# LANGUAGE NoMonomorphismRestriction #-}