[Haskell-beginners] Type of function with constant pattern
byorgey at seas.upenn.edu
Wed Apr 11 02:26:37 CEST 2012
On Tue, Apr 10, 2012 at 05:30:37PM -0400, Mike Meyer wrote:
> On Tue, 10 Apr 2012 16:57:38 -0300
> j.romildo at gmail.com wrote:
> > Hello.
> > Given the following function definitions
> > f 0 = True
> > g False = True
> > ghc infers the following types for the functions:
> > f :: (Eq a, Num a) => a -> Bool
> > g :: Bool -> Bool
> > Why f has "Eq a" in the context in ts type, and g does not?
> Bool is an instance of Eq, so there's no need to say that your
> (non-existent) type variable has that constraint.
This is not really the reason; no instance of Eq for Bool is required.
Note that you can even pattern-match like this on a type which is not
an instance of Eq:
data Foo = Bar | Baz
f Bar = True
Here the type of f is inferred as Foo -> Bool, even though there is
no instance of Eq for Foo. Pattern-matching is more fundamental than
The reason Eq is needed for the definition f 0 = True is that 0 is
not actually a constructor. Numeric literal patterns are provided as
a convenience, but they desugar into a guard of the form
f x | x == 0 = ...
Hence, an instance of Eq is needed.
More information about the Beginners