« Damselfly | Main | Robber Fly »
Tuesday
Jun292010

Another Reason to Learn Haskell

From Real World Haskell (O'Sullivan, Goerzen and Stewart, O'Reilly, 2009, page 38):

In "Function Types and Purity" on page 27 we talked about figuring out the behaviour of a function based on its type signature.  We can apply the same kind of reasoning to polymorphic functions.  Let's look again at fst:

  ghci :type fst
fst :: (a, b) -> a

First of all, notice that its argument contains two type variables, a and b, signifying that the elements of the tuple can be of different types.

The result type of fst is a.  We've already mentioned that parameteric polymorphism makes the real type inaccessible.  fst doesn't have enough information to construct a value of type a, nor can it turn an a into a b.  So the only possible valid behaviour (omitting infinite loops or crashes) it can have is to return the first element of the pair.

...

There is a deep mathematical sense in which any nonpathological function of type (a,b) -> a must do exactly what fst does.  ...

If this doesn't surpise you when you first come across it, then you haven't been paying attention.

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.
Author Email (optional):
Author URL (optional):
Post:
 
All HTML will be escaped. Hyperlinks will be created for URLs automatically.