[Haskell-beginners] Why the length function I wrote has such a
type signature?
Daniel Fischer
daniel.is.fischer at web.de
Fri Nov 12 15:12:48 EST 2010
On Friday 12 November 2010 20:14:25, Tom Murphy wrote:
> > And the type signature given by ghci is
> >
> >> myLength :: (Num t1) => [t] -> t1
>
> But why is the signature not written as:
> myLength :: [t] -> (Num t1) => t1
> or something similar?
>
> I thought that the Num typeclass being first implied that it was the
> function's first argument.
A type signature like myLength's consists of two parts,
- a context; here (Num t1)
- the part giving the type (subject to the constraints in the context).
The language definition says the context comes first, then "=>", finally
the type.
If contexts were always written next to the type they apply to, it would
lead to unreadable type signatures and repetition (the same constraint can
apply to several type variables).
Not to mention multi parameter type classes.
Strictly speaking, there's a third part, the quantification, but that's
usually left implicit (explicit foralls require a language extension).
So the full type is
myLength :: forall a n. (Num n) => [a] -> n
for all types a and n, if n is an instance of Num, myLength has (can have)
the type [a] -> n.
More information about the Beginners
mailing list