Haskell type variables

Monday, 1st June, 2009

Real World Haskell
Chapter 3: Defining types, streamlining functions
Section: A More Controlled Approach

-- file:ch03/MySecond.hs
-- edited excerpt

-- safeSecond :: [a] -> Maybe a

safeSecond [] = Nothing
safeSecond xs = if null (tail xs)
                then Nothing
                else Just (head (tail xs))

-- tidySecond :: [a] -> Maybe a

tidySecond (_:x:_) = Just x
tidySecond _       = Nothing

In December, Helge Stenström made an interesting comment about the above code:

If the type declarations using :: are omitted from safeSecond and tidySecond, they have visually different types, at least in ghci.

safeSecond :: [a] -> Maybe a
tidySecond :: [t] -> Maybe t

Why is it so?

In Hugs both functions have the same type [a] -> Maybe a.

The ghci effect is reproduced in simpler code:

safe xs = head xs
tidy (x:_) = x

In ghci:

*Main> :type safe
safe :: [a] -> a
*Main> :type tidy
tidy :: [t] -> t

I asked about this on Haskell-beginners and got some interesting replies (of which my understanding has a comfortable vagueness). Here is the last reply:

On Sun, May 31, 2009 at 05:42:44PM +0200, Daniel Fischer wrote:
> But that has nothing to do with the phenomenon, in the inferred type signatures of
> safeSecond and tidySecond, the ‘a’ resp. ‘t’ are both type variables of kind *.
> The only difference is that in one case the name supply delivered ‘a’ and in the other it
> delivered ‘t’.

I think one source of difference is that ghci tries to maintain type
variable names from declared type signatures. So perhaps one of the
library functions used to define ‘safeSecond’ has an explicitly
declared type signature that mentions ‘a’, and a library function used
to defined ‘tidySecond’ has one that mentions ‘t’.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: