[Haskell-cafe] Why I Love Haskell In One Simple Example

Thomas Jäger thjaeger at gmail.com
Tue Jun 28 06:18:26 EDT 2005

Hi Mads,

Since ghc-6.4 there's another feature that is enabled by such explicit
foralls in type signatures, namely scoped type variables. Consider
> foo :: Num a => a -> a -> a
> foo x y = x + z where
>   z = 2 * y
Now since adding type signatures is a good thing, you want to give z
an explicit type signature. But |z :: a| fails with an "Inferred type
is less polymorphic than expected" error because the |a| actually
means |forall a. a| and not the |a| from foo's type signature. The
classical way (still, it's an extension implemented in hugs and all
versions of ghc i'm aware of) to bring the in scope by binding it like
> foo (x :: a) y = x + y where
This is fine in such simple examples, but often gets tedious and
clutters up the definition by weird type annotations. Therefore
ghc-6.4 implements the great feature that the |a| from foo's type
signature is automatically brought into scope if you explicitely
quantify it with a forall.

Aside: A small disadvantage seems to be that you can only scope over
either all or none of the type variables in your signature. However,
> foo :: forall a. Num a => (forall b. ...)
will bring the variable a into scope, but not b and is otherwise equivalent to
> foo :: forall a b. Num a => ...

On 6/27/05, Mads Lindstrøm <mads_lindstroem at yahoo.dk> wrote:
> I had newer seen anybody use "forall a." in function signatures before,
> and therefore was curious about its effect. This is probably do to my
> inexperience regarding Haskell. However, I tried to remove it and wrote
> this instead:
> test :: (Num a) => a
> and the code still compiled and seems to run fine. Also using the
> prettyShow and rpnShow functions. So, why are you using the forall
> keyword? (this is not meant as a critique, i am just curious)
> I tried to find documentation about the use of the forall keyword in
> respect to functions (I do know about it in with respect to
> existentially quantified types), but with no luck. So, if anybody has
> some good pointers, please let med know about it.
A great recource is
Bookmark this page and come back to it every once in a while - there
are just so many treasures in it - one of my favorites is "7.4.12.
Generalised derived instances for newtypes"


More information about the Haskell-Cafe mailing list