O'Reilly logo

Real World Haskell by Donald Bruce Stewart, Bryan O'Sullivan, John Goerzen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Useful Composite Data Types: Lists and Tuples

A composite data type is constructed from other types. The most common composite data types in Haskell are lists and tuples.

We’ve already seen the list type mentioned earlier in the Strings and Characters, where we found that Haskell represents a text string as a list of Char values, and that the type list of Char is written [Char].

The head function returns the first element of a list:

ghci> head [1,2,3,4]
1
ghci> head ['a','b','c']
'a'

Its counterpart, tail, returns all but the head of a list:

ghci> tail [1,2,3,4]
[2,3,4]
ghci> tail [2,3,4]
[3,4]
ghci> tail [True,False]
[False]
ghci> tail "list"
"ist"
ghci> tail []
*** Exception: Prelude.tail: empty list

As you can see, we can apply head and tail to lists of different types. Applying head to a [Char] value returns a Char value, while applying it to a [Bool] value returns a Bool value. The head function doesn’t care what type of list it deals with.

Because the values in a list can have any type, we call the list type polymorphic.[4] When we want to write a polymorphic type, we use a type variable, which must begin with a lowercase letter. A type variable is a placeholder, where we’ll eventually substitute a real type.

We can write the type list of a by enclosing the type variable in square brackets: [a]. This amounts to saying, I don’t care what type I have; I can make a list with it.

Distinguishing type names and type variables

We can now see why a type name must start with an uppercase ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required