In this chapter we introduce types and classes, two of the most fundamental concepts in Haskell. We start by explaining what types are and how they are used in Haskell, then present a number of basic types and ways to build larger types by combining smaller types, discuss function types in more detail, and conclude with the concepts of polymorphic types and type classes.
Basic concepts
A type is a collection of related values. For example, the type Bool contains the two logical values False and True, while the type Bool -> Bool contains all functions that map arguments from Bool to results from Bool, such as the logical negation function not. We use the notation v :: T to mean that v is a value in the type T, and say that v has type T. For example:
False :: Bool
True :: Bool
not :: Bool -> Bool
More generally, the symbol :: can also be used with expressions that have not yet been evaluated, in which case the notation e :: T means that evaluation of the expression e will produce a value of type T. For example:
not False :: Bool
not True :: Bool
not (not False) :: Bool
In Haskell, every expression must have a type, which is calculated prior to evaluating the expression by a process called type inference. The key to this process is the following simple typing rule for function application, which states that if f is a function that maps arguments of type A to results of type B, and e is an expression of type A, then the application f e has type B:
For example, the typing not False :: Bool can be inferred from this rule using the fact that not :: Bool -> Bool and False :: Bool. On the other hand, the expression not 3 does not have a type under the above rule, because this would require that 3 :: Bool, which is not valid because 3 is not a logical value. Expressions such as not 3 that do not have a type are said to contain a type error, and are deemed to be invalid expressions.
Because type inference precedes evaluation, Haskell programs are type safe, in the sense that type errors can never occur during evaluation.
Review the options below to login to check your access.
Log in with your Cambridge Aspire website account to check access.
If you believe you should have access to this content, please contact your institutional librarian or consult our FAQ page for further information about accessing our content.