Type signature

From HaskellWiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

A type signature is a line like

inc :: Num a => a -> a

that tells, what is the type of a variable. In the example inc is the variable, Num a => is the context and a -> a is its type, namely a function type with the kind * -> *.

A very simple example looks like this

title :: String

which restricts the variable title to the the type String. Binding a value of any other type will lead to a type missmatch. For example binding 42 to title by writing title = 42 will lead to an error looking like this in ghc 7.10

    No instance for (Num String) arising from the literal 42
    In the expression: 42
    In an equation for title: title = 42

To better understand the error message, take a look at the types, in ghci you can use the `:t ` command which will show you the type for a given expression

>:t title
title :: String
>:t 42
42 :: Num a => a

If instead declaring the types like in this example

title :: String
value :: Integer

value = 42
title = value

the error message becomes clearer

    Couldn`t match type Integer with [Char]
    Expected type: String
      Actual type: Integer
    In the expression: value
    In an equation for title: title = value

but there is still room for confusion because the first lines mentiones the type `[Char]` which does not appear in the type signatures in the example. This comes form the fact that String is just a renaming for [Char]. The compiler only typechecks the expressions after resolving the renaming.

It is considered good style to add a type signature to every top-level variable.

References