🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Type Variables

A type variable is a lower-case name in a signature that stands for any one type. One signature with a variable can describe a function that works with many types.

One variable stands for the item type

firstOf returns the first item of a list. The variable a stands for whatever type the items have.

firstOf :: [a] -> a
firstOf xs = head xs

main :: IO ()
main = print (firstOf [10, 20, 30])

The same function works with text

A String is a list of Char values. Here a stands for Char, so firstOf returns a Char.

firstOf :: [a] -> a
firstOf xs = head xs

main :: IO ()
main = print (firstOf "haskell")

Two variables can stand for different types

pairUp joins two inputs into a pair. The first input has type a and the second has type b.

pairUp :: a -> b -> (a, b)
pairUp x y = (x, y)

main :: IO ()
main = print (pairUp 7 "seven")

Example

firstOf :: [a] -> a
firstOf xs = head xs

wrap :: a -> [a]
wrap x = [x]

swap :: (a, b) -> (b, a)
swap (x, y) = (y, x)

main :: IO ()
main = print (firstOf [3, 4], wrap True, swap (True, 9))

Key points

  • Variable form: a type variable starts with a lower-case letter, like a or b.
  • Any one type: in firstOf :: [a] -> a, the letter a can be Int, Char, Bool, or another type.
  • Same letter, same type: every a in one signature stands for the same type.
  • Two letters: a and b in one signature can stand for different types.
  • Capital names: a name with a capital letter, like Int, is one fixed type.

In this example, firstOf uses a for Int and returns 3. wrap uses a for Bool and builds the one-item list [True]. swap uses a for Bool and b for Int, and it returns the pair flipped as (9, True). Each function works because its signature names types with variables instead of one fixed type.

Note

a type variable appears in signatures, not as a value a program can store.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

In the signature firstOf :: [a] -> a, what does the type variable a stand for?