🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Type Aliases

A type alias is a new name for a type that already exists. The type keyword gives the existing type another name.

An alias names a String type

Name is another name for String. The greet function uses Name in its signature.

type Name = String

greet :: Name -> String
greet name = "Hello, " ++ name

main :: IO ()
main = putStrLn (greet "Ana")

An alias names a tuple type

Point is another name for a pair of Double values. xOf reads the first coordinate of a Point.

type Point = (Double, Double)

xOf :: Point -> Double
xOf (x, _) = x

main :: IO ()
main = print (xOf (3.5, 9.0))

An alias value still works as the original type

The binding name has type Name, which is String. The String functions length and ++ work on it directly.

type Name = String

name :: Name
name = "Ana"

main :: IO ()
main = print (length name, name ++ " Verma")

Example

type Name = String

type Point = (Double, Double)

customer :: Name
customer = "Mina"

home :: Point
home = (2.5, 4.0)

labelPoint :: Name -> Point -> (Name, Double)
labelPoint name (x, _) = (name, x)

main :: IO ()
main = print (labelPoint customer home)

Key points

  • Alias form: type Name = String gives the String type the extra name Name.
  • Same type: an alias and the original name stand for exactly the same type.
  • Clear signatures: an alias can say what a value means, like Point for a pair of coordinates.
  • Tuple alias: type Point = (Double, Double) names a pair of two Double values.
  • Free mixing: a value of the alias type works anywhere the original type works.

In this example, Name is an alias for String and Point is an alias for a pair of Double values. customer holds the text "Mina" and home holds the pair (2.5, 4.0). labelPoint pairs the name with the first coordinate. The printed result pairs "Mina" with 2.5.

Note

an alias adds no new checks, so a wrong pair can still be passed where a Point is expected.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What does the line type Point = (Double, Double) create?