[Haskell-cafe] Typeclass constraints not inferred when defining a function
stphndemos at gmail.com
Thu Feb 9 18:20:12 UTC 2017
A professor showed me a function today that looks like this -
`append = flip (foldr (:))`
GHC spits back an error when this is compiled -
• Ambiguous type variable ‘t0’ arising from a use of ‘foldr’
prevents the constraint ‘(Foldable t0)’ from being solved.
Relevant bindings include
append :: t0 a -> [a] -> [a] (bound at test.hs:4:1)
Probable fix: use a type annotation to specify what ‘t0’ should be.
It's obvious from this error message the problem is that the type GHC
infers doesn't include the typeclass constraint. In this case, it's
Foldable, but you can easily think of other situations where the same
error comes up with different typeclasses (a silly example that comes
to mind is `fmap (const )`). It's pretty easy to fix this error by
just providing a type for the function that is more specific than the
one GHC infers.
However, he showed me that defining the same function in ghci using a
let binding doesn't yield the same error. In fact, when using `:t`, it
shows that ghci successfully infers the typeclass constraint on the
> :t flip (foldr (:))
flip (foldr (:)) :: Foldable t => t a -> [a] -> [a]
I was wondering if anyone could explain this apparent discrepancy to me.
More information about the Haskell-Cafe