Personal tools

Type signature

From HaskellWiki

Jump to: navigation, search

A type signature is a line like

inc :: Num a => a -> a

that tells, what is the type of a variable.

In the example
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
to the the type
. Binding a value of any other type will lead to a type missmatch. For example binding
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 typeInteger’ 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
is just a renaming for
. 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.