DRAFT
This is a work in progress, not an official release of the Haskell 2010 Revised Language Report.
prev Contents next

4 Declarations and Bindings

In this chapter, we describe the syntax and informal semantics of Haskell declarations.

π‘šπ‘œπ‘‘π‘’π‘™π‘’β†’πš–πš˜πšπšžπš•πšŽπ‘šπ‘œπ‘‘π‘–π‘‘[𝑒π‘₯π‘π‘œπ‘Ÿπ‘‘π‘ ]πš πš‘πšŽπš›πšŽπ‘π‘œπ‘‘π‘¦
|π‘π‘œπ‘‘π‘¦
π‘π‘œπ‘‘π‘¦β†’{π‘–π‘šπ‘π‘‘π‘’π‘π‘™π‘ ;π‘‘π‘œπ‘π‘‘π‘’π‘π‘™π‘ }
|{π‘–π‘šπ‘π‘‘π‘’π‘π‘™π‘ }
|{π‘‘π‘œπ‘π‘‘π‘’π‘π‘™π‘ }
π‘‘π‘œπ‘π‘‘π‘’π‘π‘™π‘ β†’π‘‘π‘œπ‘π‘‘π‘’π‘π‘™1;…;π‘‘π‘œπ‘π‘‘π‘’π‘π‘™π‘›(𝑛β‰₯1)
π‘‘π‘œπ‘π‘‘π‘’π‘π‘™β†’πšπš’πš™πšŽπ‘ π‘–π‘šπ‘π‘™π‘’π‘‘π‘¦π‘π‘’=𝑑𝑦𝑝𝑒
|𝚍𝚊𝚝𝚊[π‘π‘œπ‘›π‘‘π‘’π‘₯𝑑=>]π‘ π‘–π‘šπ‘π‘™π‘’π‘‘π‘¦π‘π‘’[=π‘π‘œπ‘›π‘ π‘‘π‘Ÿπ‘ ][π‘‘π‘’π‘Ÿπ‘–π‘£π‘–π‘›π‘”]
|πš—πšŽπš πšπš’πš™πšŽ[π‘π‘œπ‘›π‘‘π‘’π‘₯𝑑=>]π‘ π‘–π‘šπ‘π‘™π‘’π‘‘π‘¦π‘π‘’=π‘›π‘’π‘€π‘π‘œπ‘›π‘ π‘‘π‘Ÿ[π‘‘π‘’π‘Ÿπ‘–π‘£π‘–π‘›π‘”]
|πšŒπš•πšŠπšœπšœ[π‘ π‘π‘œπ‘›π‘‘π‘’π‘₯𝑑=>]π‘‘π‘¦π‘π‘™π‘ π‘‘π‘¦π‘£π‘Žπ‘Ÿ[πš πš‘πšŽπš›πšŽπ‘π‘‘π‘’π‘π‘™π‘ ]
|πš’πš—πšœπšπšŠπš—πšŒπšŽ[π‘ π‘π‘œπ‘›π‘‘π‘’π‘₯𝑑=>]π‘žπ‘‘π‘¦π‘π‘™π‘ π‘–π‘›π‘ π‘‘[πš πš‘πšŽπš›πšŽπ‘–π‘‘π‘’π‘π‘™π‘ ]
|πšπšŽπšπšŠπšžπš•πš(𝑑𝑦𝑝𝑒1,…,𝑑𝑦𝑝𝑒𝑛)(𝑛β‰₯0)
|πšπš˜πš›πšŽπš’πšπš—π‘“π‘‘π‘’π‘π‘™
|𝑑𝑒𝑐𝑙
𝑑𝑒𝑐𝑙𝑠→{𝑑𝑒𝑐𝑙1;…;𝑑𝑒𝑐𝑙𝑛}(𝑛β‰₯0)
𝑑𝑒𝑐𝑙→𝑔𝑒𝑛𝑑𝑒𝑐𝑙
|(π‘“π‘’π‘›π‘™β„Žπ‘ |π‘π‘Žπ‘‘)π‘Ÿβ„Žπ‘ 
𝑐𝑑𝑒𝑐𝑙𝑠→{𝑐𝑑𝑒𝑐𝑙1;…;𝑐𝑑𝑒𝑐𝑙𝑛}(𝑛β‰₯0)
𝑐𝑑𝑒𝑐𝑙→𝑔𝑒𝑛𝑑𝑒𝑐𝑙
|(π‘“π‘’π‘›π‘™β„Žπ‘ |π‘£π‘Žπ‘Ÿ)π‘Ÿβ„Žπ‘ 
𝑖𝑑𝑒𝑐𝑙𝑠→{𝑖𝑑𝑒𝑐𝑙1;…;𝑖𝑑𝑒𝑐𝑙𝑛}(𝑛β‰₯0)
𝑖𝑑𝑒𝑐𝑙→(π‘“π‘’π‘›π‘™β„Žπ‘ |π‘£π‘Žπ‘Ÿ)π‘Ÿβ„Žπ‘ 
|(empty)
π‘”π‘’π‘›π‘‘π‘’π‘π‘™β†’π‘£π‘Žπ‘Ÿπ‘ ::[π‘π‘œπ‘›π‘‘π‘’π‘₯𝑑=>]𝑑𝑦𝑝𝑒(type signature)
|𝑓𝑖π‘₯𝑖𝑑𝑦[π‘–π‘›π‘‘π‘’π‘”π‘’π‘Ÿ]π‘œπ‘π‘ (fixity declaration)
|(empty declaration)
π‘œπ‘π‘ β†’π‘œπ‘1,…,π‘œπ‘π‘›(𝑛β‰₯1)
π‘£π‘Žπ‘Ÿπ‘ β†’π‘£π‘Žπ‘Ÿ1,…,π‘£π‘Žπ‘Ÿπ‘›(𝑛β‰₯1)
𝑓𝑖π‘₯π‘–π‘‘π‘¦β†’πš’πš—πšπš’πš‘πš•|πš’πš—πšπš’πš‘πš›|πš’πš—πšπš’πš‘

The declarations in the syntactic category π‘‘π‘œπ‘π‘‘π‘’π‘π‘™π‘  are only allowed at the top level of a Haskell module (see ChapterΒ 5), whereas 𝑑𝑒𝑐𝑙𝑠 may be used either at the top level or in nested scopes (i.e. those within a let or where construct).

For exposition, we divide the declarations into three groups: user-defined datatypes, consisting of type, newtype, and data declarations (SectionΒ 4.2); type classes and overloading, consisting of class, instance, and default declarations (SectionΒ 4.3); and nested declarations, consisting of value bindings, type signatures, and fixity declarations (SectionΒ 4.4).

Haskell has several primitive datatypes that are β€œhard-wired” (such as integers and floating-point numbers), but most β€œbuilt-in” datatypes are defined with normal Haskell code, using normal type and data declarations. These β€œbuilt-in” datatypes are described in detail in SectionΒ 6.1.

4.1 Overview of Types and Classes

Haskell uses a traditional Hindley-Milner polymorphic type system to provide a static type semantics [4], [5], but the type system has been extended with type classes (or just classes) that provide a structured way to introduce overloaded functions.

A class declaration (SectionΒ 4.3.1) introduces a new type class and the overloaded operations that must be supported by any type that is an instance of that class. An instance declaration (SectionΒ 4.3.2) declares that a type is an instance of a class and includes the definitions of the overloaded operationsβ€”called class methodsβ€”instantiated on the named type.

For example, suppose we wish to overload the operations (+) and negate on types Int and Float. We introduce a new type class called Num:

  class Num a  where          -- simplified class declaration for Num
    (+)    :: a -> a -> a     -- (Num is defined in the Prelude)
    negate :: a -> a

This declaration may be read β€œa type a is an instance of the class Num if there are class methods (+) and negate, of the given types, defined on it.β€β€œ

We may then declare Int and Float to be instances of this class:

  instance Num Int  where     -- simplified instance of Num Int
    x + y       =  addInt x y
    negate x    =  negateInt x
  
  instance Num Float  where   -- simplified instance of Num Float
    x + y       =  addFloat x y
    negate x    =  negateFloat x

where addInt, negateInt, addFloat, and negateFloat are assumed in this case to be primitive functions, but in general could be any user-defined function. The first declaration above may be read β€œInt is an instance of the class Num as witnessed by these definitions (i.e.Β class methods) for (+) and negate.”

More examples of type classes can be found in the papers by Jones [6] or Wadler and Blott [7]. The term β€œtype class” was used to describe the original Haskell 1.0 type system; β€œconstructor class” was used to describe an extension to the original type classes. There is no longer any reason to use two different terms: in this report, β€œtype class” includes both the original Haskell type classes and the constructor classes introduced by Jones.

4.1.1 Kinds

To ensure that they are valid, type expressions are classified into different kinds, which take one of two possible forms:

Kind inference checks the validity of type expressions in a similar way that type inference checks the validity of value expressions. However, unlike types, kinds are entirely implicit and are not a visible part of the language. Kind inference is discussed in SectionΒ 4.6.

4.1.2 Syntax of Types

𝑑𝑦𝑝𝑒→𝑏𝑑𝑦𝑝𝑒[->𝑑𝑦𝑝𝑒](function type)
𝑏𝑑𝑦𝑝𝑒→[𝑏𝑑𝑦𝑝𝑒]π‘Žπ‘‘π‘¦π‘π‘’(type application)
π‘Žπ‘‘π‘¦π‘π‘’β†’π‘”π‘‘π‘¦π‘π‘œπ‘›
|π‘‘π‘¦π‘£π‘Žπ‘Ÿ
|(𝑑𝑦𝑝𝑒1,…,π‘‘π‘¦π‘π‘’π‘˜)(tuple type, π‘˜β‰₯2)
|[𝑑𝑦𝑝𝑒](list type)
|(𝑑𝑦𝑝𝑒)(parenthesized constructor)
π‘”π‘‘π‘¦π‘π‘œπ‘›β†’π‘žπ‘‘π‘¦π‘π‘œπ‘›
|()(unit type)
|[](list constructor)
|(->)(function constructor)
|(,{,})(tupling constructors)

The syntax for Haskell type expressions is given above. Just as data values are built using data constructors, type values are built from type constructors. As with data constructors, the names of type constructors start with uppercase letters. Unlike data constructors, infix type constructors are not allowed (other than (->)).

The main forms of type expression are as follows:

  1. Type variables, written as identifiers beginning with a lowercase letter. The kind of a variable is determined implicitly by the context in which it appears.

  2. Type constructors. Most type constructors are written as an identifier beginning with an uppercase letter. For example:

    • Char, Int, Integer, Float, Double and Bool are type constants with kind βˆ—.
    • Maybe and IO are unary type constructors, and treated as types with kind βˆ—β†’βˆ—.
    • The declarations data T ... or newtype T ... add the type constructor T to the type vocabulary. The kind of T is determined by kind inference.

    Special syntax is provided for certain built-in type constructors:

    • The trivial type is written as () and has kind βˆ—. It denotes the β€œnullary tuple” type, and has exactly one value, also written () (see SectionΒ 3.9 and SectionΒ 6.1.5).
    • The function type is written as (->) and has kind βˆ—β†’βˆ—β†’βˆ—.
    • The list type is written as [] and has kind βˆ—β†’βˆ—.
    • The tuple types are written as (,), (,,), and so on. Their kinds are βˆ—β†’βˆ—β†’βˆ—,βˆ—β†’βˆ—β†’βˆ—β†’βˆ—, and so on.

    Use of the (->) and [] constants is described in more detail below.

  3. Type application. If 𝑑1 is a type of kind πœ…1β†’πœ…2 and 𝑑2 is a type of kind πœ…1, then 𝑑1 𝑑2 is a type expression of kind πœ…2.

  4. A parenthesized type, having form (𝑑), is identical to the type 𝑑.

For example, the type expression IO a can be understood as the application of a constant, IO, to the variable a. Since the IO type constructor has kind βˆ—β†’βˆ—, it follows that both the variable a and the whole expression, IO a, must have kind βˆ—. In general, a process of kind inference (see SectionΒ 4.6) is needed to determine appropriate kinds for user-defined datatypes, type synonyms, and classes.

Special syntax is provided to allow certain type expressions to be written in a more traditional style:

  1. A function type has the form 𝑑1→𝑑2, which is equivalent to the type (β†’)𝑑1𝑑2. Function arrows associate to the right. For example, Int -> Int -> Float means Int -> (Int -> Float).
  2. A tuple type has the form (𝑑1,…,π‘‘π‘˜), where π‘˜β‰₯2, which is equivalent to the type (,…,)𝑑1β€¦π‘‘π‘˜ where there are π‘˜βˆ’1 commas between the parenthesis. It denotes the type of π‘˜-tuples with the first component of type 𝑑1, the second component of type 𝑑2, and so on (see SectionΒ 3.8 and SectionΒ 6.1.4).
  3. A list type has the form [𝑑], which is equivalent to the type []𝑑. It denotes the type of lists with elements of type 𝑑 (see SectionΒ 3.7 and SectionΒ 6.1.3).

These special syntactic forms always denote the built-in type constructors for functions, tuples, and lists, regardless of what is in scope. In a similar way, the prefix type constructors (->), [], (), (,), and so on, always denote the built-in type constructors; they cannot be qualified, nor mentioned in import or export lists (ChapterΒ 5). (Hence the special production, β€œgtycon”, above.)

Although the list and tuple types have special syntax, their semantics is the same as the equivalent user-defined algebraic data types.

Notice that expressions and types have a consistent syntax. If 𝑑𝑖 is the type of expression or pattern 𝑒𝑖, then the expressions (\ e1 -> e2), [e1], and (t1 -> t2), [t1], and (t1, t2), respectively.

With one exception (that of the distinguished type variable in a class declaration (SectionΒ 4.3.1)), the type variables in a Haskell type expression are all assumed to be universally quantified; there is no explicit syntax for universal quantification [5]. For example, the type expression a -> a denotes the type βˆ€π‘Ž.π‘Žβ†’π‘Ž. For clarity, however, we often write quantification explicitly when discussing the types of Haskell programs. When we write an explicitly quantified type, the scope of the βˆ€ extends as far to the right as possible; for example, βˆ€π‘Ž.π‘Žβ†’π‘Ž means βˆ€π‘Ž.(π‘Žβ†’π‘Ž).

4.1.3 Syntax of Class Assertions and Contexts

π‘π‘œπ‘›π‘‘π‘’π‘₯π‘‘β†’π‘π‘™π‘Žπ‘ π‘ 
|(π‘π‘™π‘Žπ‘ π‘ 1,…,π‘π‘™π‘Žπ‘ π‘ π‘›)(𝑛β‰₯0)
π‘π‘™π‘Žπ‘ π‘ β†’π‘žπ‘‘π‘¦π‘π‘™π‘ π‘‘π‘¦π‘£π‘Žπ‘Ÿ
|π‘žπ‘‘π‘¦π‘π‘™π‘ (π‘‘π‘¦π‘£π‘Žπ‘Ÿπ‘Žπ‘‘π‘¦π‘π‘’1β€¦π‘Žπ‘‘π‘¦π‘π‘’π‘›)(𝑛β‰₯1)
π‘žπ‘‘π‘¦π‘π‘™π‘ β†’[π‘šπ‘œπ‘‘π‘–π‘‘.]𝑑𝑦𝑐𝑙𝑠
π‘‘π‘¦π‘π‘™π‘ β†’π‘π‘œπ‘›π‘–π‘‘
π‘‘π‘¦π‘£π‘Žπ‘Ÿβ†’π‘£π‘Žπ‘Ÿπ‘–π‘‘

A class assertion has form π‘žπ‘‘π‘¦π‘π‘™π‘ π‘‘π‘¦π‘£π‘Žπ‘Ÿ, and indicates the membership of the type π‘‘π‘¦π‘£π‘Žπ‘Ÿ in the class π‘žπ‘‘π‘¦π‘π‘™π‘ . A class identifier begins with an uppercase letter. A context consists of zero or more class assertions, and has the general form

(𝐢1𝑒1,…,𝐢𝑛𝑒𝑛)

where 𝐢1,…,𝐢𝑛 are class identifiers, and each of the 𝑒1,…,𝑒𝑛 is either a type variable, or the application of type variable to one or more types. The outer parentheses may be omitted when 𝑛=1. In general, we use 𝑐π‘₯ to denote a context and we write 𝑐π‘₯=>𝑑 to indicate the type 𝑑 restricted by the context 𝑐π‘₯. The context 𝑐π‘₯ must only contain type variables referenced in 𝑑. For convenience, we write 𝑐π‘₯=>𝑑 even if the context 𝑐π‘₯ is empty, although in this case the concrete syntax contains no =>.

4.1.4 Semantics of Types and Classes

In this section, we provide informal details of the type system. (Wadler and Blott [7] and Jones [6] discuss type and constructor classes, respectively, in more detail.)

The Haskell type system attributes a type to each expression in the program. In general, a type is of the form βˆ€π‘’_.𝑐π‘₯⇒𝑑, where 𝑒_ is a set of type variables 𝑒1,…,𝑒𝑛. In any such type, any of the universally-quantified type variables 𝑒𝑖 that are free in 𝑐π‘₯ must also be free in 𝑑. Furthermore, the context 𝑐π‘₯ must be of the form given above in SectionΒ 4.1.3. For example, here are some valid types:

  Eq a => a -> a
  (Eq a, Show a, Eq b) => [a] -> [b] -> String
  (Eq (f a), Functor f) => (a -> b) -> f a -> f b -> Bool

In the third type, the constraint Eq (f a) cannot be made simpler because f is universally quantified.

The type of an expression 𝑒 depends on a type environment that gives types for the free variables in 𝑒, and a class environment that declares which types are instances of which classes (a type becomes an instance of a class only via the presence of an instance declaration or a deriving clause).

Types are related by a generalization preorder (specified below); the most general type, up to the equivalence induced by the generalization preorder, that can be assigned to a particular expression (in a given environment) is called its principal type. Haskell’s extended Hindley-Milner type system can infer the principal type of all expressions, including the proper use of overloaded class methods (although certain ambiguous overloadings could arise, as described in SectionΒ 4.3.4). Therefore, explicit typings (called type signatures) are usually optional (see SectionΒ 3.16 and SectionΒ 4.4.1).

The type βˆ€π‘’_.𝑐π‘₯1⇒𝑑1 more general than the type βˆ€π‘€_.𝑐π‘₯2⇒𝑑2 if and only if there is a substitution 𝑆 whose domain is 𝑒_ such that:

A value of type βˆ€π‘’_.𝑐π‘₯⇒𝑑, may be instantiated at types 𝑠_ if and only if the context 𝑐π‘₯[𝑠_𝑒_] holds. For example, consider the function double:

double x = x + x

The most general type of double is βˆ€π‘Ž.π™½πšžπš–π‘Žβ‡’π‘Žβ†’π‘Ž. double may be applied to values of type Int (instantiating π‘Ž to Int), since Num Int holds, because Int is an instance of the class Num. However, double may not normally be applied to values of type Char, because Char is not normally an instance of class Num. The user may choose to declare such an instance, in which case double may indeed be applied to a Char.

4.2 User-Defined Datatypes

In this section, we describe algebraic datatypes (data declarations), renamed datatypes (newtype declarations), and type synonyms (type declarations). These declarations may only appear at the top level of a module.

4.2.1 Algebraic Datatype Declarations

π‘‘π‘œπ‘π‘‘π‘’π‘π‘™β†’πšπšŠπšπšŠ[π‘π‘œπ‘›π‘‘π‘’π‘₯𝑑=>]π‘ π‘–π‘šπ‘π‘™π‘’π‘‘π‘¦π‘π‘’[=π‘π‘œπ‘›π‘ π‘‘π‘Ÿπ‘ ][π‘‘π‘’π‘Ÿπ‘–π‘£π‘–π‘›π‘”]
π‘ π‘–π‘šπ‘π‘™π‘’π‘‘π‘¦π‘π‘’β†’π‘‘π‘¦π‘π‘œπ‘›π‘‘π‘¦π‘£π‘Žπ‘Ÿ1β€¦π‘‘π‘¦π‘£π‘Žπ‘Ÿπ‘˜(π‘˜β‰₯0)
π‘π‘œπ‘›π‘ π‘‘π‘Ÿπ‘ β†’π‘π‘œπ‘›π‘ π‘‘π‘Ÿ1|…|π‘π‘œπ‘›π‘ π‘‘π‘Ÿπ‘›(𝑛β‰₯1)
π‘π‘œπ‘›π‘ π‘‘π‘Ÿβ†’π‘π‘œπ‘›[!]π‘Žπ‘‘π‘¦π‘π‘’1…[!]π‘Žπ‘‘π‘¦π‘π‘’π‘˜(arity π‘π‘œπ‘›=π‘˜, π‘˜β‰₯0)
|(𝑏𝑑𝑦𝑝𝑒|!π‘Žπ‘‘π‘¦π‘π‘’)π‘π‘œπ‘›π‘œπ‘(𝑏𝑑𝑦𝑝𝑒|!π‘Žπ‘‘π‘¦π‘π‘’)(infix π‘π‘œπ‘›π‘œπ‘)
|π‘π‘œπ‘›{𝑓𝑖𝑒𝑙𝑑𝑑𝑒𝑐𝑙1,…,𝑓𝑖𝑒𝑙𝑑𝑑𝑒𝑐𝑙𝑛}(𝑛β‰₯0)
π‘“π‘–π‘’π‘™π‘‘π‘‘π‘’π‘π‘™β†’π‘£π‘Žπ‘Ÿπ‘ ::(𝑑𝑦𝑝𝑒|!π‘Žπ‘‘π‘¦π‘π‘’)
π‘‘π‘’π‘Ÿπ‘–π‘£π‘–π‘›π‘”β†’πšπšŽπš›πš’πšŸπš’πš—πš(π‘‘π‘π‘™π‘Žπ‘ π‘ |(π‘‘π‘π‘™π‘Žπ‘ π‘ 1,…,π‘‘π‘π‘™π‘Žπ‘ π‘ π‘›))(𝑛β‰₯0)
π‘‘π‘π‘™π‘Žπ‘ π‘ β†’π‘žπ‘‘π‘¦π‘π‘™π‘ 

The precedence for π‘π‘œπ‘›π‘ π‘‘π‘Ÿ is the same as that for expressionsβ€”normal constructor application has higher precedence than infix constructor application (thus a : Foo a parses as a : (Foo a)).

An algebraic datatype declaration has the form:

πšπšŠπšπšŠπ‘π‘₯=>𝑇𝑒1β€¦π‘’π‘˜=𝐾1𝑑11…𝑑1π‘˜1|…|𝐾𝑛𝑑𝑛1β€¦π‘‘π‘›π‘˜π‘›

where 𝑐π‘₯ is a context. This declaration introduces a new type constructor 𝑇 with zero or more constituent data constructors 𝐾1,…𝐾𝑛. In this Report, the unqualified term β€œconstructor” always means β€œdata constructor”.

The types of the data constructors are given by:

𝐾𝑖::βˆ€π‘’1β€¦π‘’π‘˜.𝑐π‘₯𝑖⇒𝑑𝑖1β†’β€¦β†’π‘‘π‘–π‘˜π‘–β†’(𝑇 𝑒1β€¦π‘’π‘˜)

where 𝑐π‘₯𝑖 is the largest subset of 𝑐π‘₯ that constrains only those type variables free in the types 𝑑𝑖1β€¦π‘‘π‘–π‘˜π‘–. The type variables 𝑒1 through π‘’π‘˜ must be distinct and may appear in 𝑐π‘₯ and the 𝑑𝑖𝑗; it is a static error for any other type variable to appear in 𝑐π‘₯ or on the right-hand-side. The new type constant 𝑇 has a kind of the form πœ…1β†’β€¦β†’πœ…π‘˜β†’βˆ— where the kinds πœ…π‘– of the argument variables 𝑒𝑖 are determined by kind inference as described in SectionΒ 4.6. This means that 𝑇 may be used in type expressions with anywhere between 0 and π‘˜ arguments.

For example, the declaration

data Eq a => Set a = NilSet | ConsSet a (Set a)

introduces a type constructor Set of kind βˆ—β†’βˆ—, and constructors NilSet and ConsSet with types

NilSet::βˆ€π‘Ž.πš‚πšŽπšπ‘Ž
ConsSet::βˆ€π‘Ž.π™΄πššπ‘Žβ‡’π‘Žβ†’πš‚πšŽπšπ‘Žβ†’πš‚πšŽπšπ‘Ž

In the example given, the overloaded type for ConsSet ensures that ConsSet can only be applied to values whose type is an instance of the class Eq. Pattern matching against ConsSet also gives rise to an Eq a constraint. For example:

  f (ConsSet a s) = a

the function f has inferred type Eq a => Set a -> a. The context in the data declaration has no other effect whatsoever.

The visibility of a datatype’s constructors (i.e.Β the β€œabstractness” of the datatype) outside of the module in which the datatype is defined is controlled by the form of the datatype’s name in the export list as described in SectionΒ 5.8.

The optional deriving part of a data declaration has to do with derived instances, and is described in SectionΒ 4.3.3.

Labelled Fields A data constructor of arity π‘˜ creates an object with π‘˜ components. These components are normally accessed positionally as arguments to the constructor in expressions or patterns. For large datatypes it is useful to assign field labels to the components of a data object. This allows a specific field to be referenced independently of its location within the constructor.

A constructor definition in a data declaration may assign labels to the fields of the constructor, using the record syntax (𝐢 { … }). Constructors using field labels may be freely mixed with constructors without them. A constructor with associated field labels may still be used as an ordinary constructor; features using labels are simply a shorthand for operations using an underlying positional constructor. The arguments to the positional constructor occur in the same order as the labeled fields. For example, the declaration

  data C = F { f1,f2 :: Int, f3 :: Bool }

defines a type and constructor identical to the one produced by

  data C = F Int Int Bool

Operations using field labels are described in SectionΒ 3.15. A data declaration may use the same field label in multiple constructors as long as the typing of the field is the same in all cases after type synonym expansion. A label cannot be shared by more than one type in scope. Field names share the top level namespace with ordinary variables and class methods and must not conflict with other top level names in scope.

The pattern F { } matches any value built with constructor F, whether or not F was declared with record syntax.

Strictness Flags Whenever a data constructor is applied, each argument to the constructor is evaluated if and only if the corresponding type in the algebraic datatype declaration has a strictness flag, denoted by an exclamation point, β€œ!”. Lexically, β€œ!” is an ordinary varsym not a π‘Ÿπ‘’π‘ π‘’π‘Ÿπ‘£π‘’π‘‘π‘œπ‘; it has special significance only in the context of the argument types of a data declaration.

Translation: A declaration of the form

πšπšŠπšπšŠπ‘π‘₯⇒𝑇𝑒1β€¦π‘’π‘˜=…|𝐾𝑠1…𝑠𝑛|…

where each 𝑠𝑖 is either of the form !𝑑𝑖 or 𝑑𝑖, replaces every occurrence of 𝐾 in an expression by

(\π‘₯1…π‘₯𝑛->(((πΎπ‘œπ‘1π‘₯1)π‘œπ‘2π‘₯2)…)π‘œπ‘π‘›π‘₯𝑛)

where π‘œπ‘π‘– is the non-strict apply function $ if 𝑠𝑖 is of the form 𝑑𝑖, and π‘œπ‘π‘– is the strict apply function $! (see SectionΒ 6.2) if 𝑠𝑖 is of the form !𝑑𝑖. Pattern matching on 𝐾 is not affected by strictness flags.

4.2.2 Type Synonym Declarations

π‘‘π‘œπ‘π‘‘π‘’π‘π‘™β†’πšπš’πš™πšŽπ‘ π‘–π‘šπ‘π‘™π‘’π‘‘π‘¦π‘π‘’=𝑑𝑦𝑝𝑒
π‘ π‘–π‘šπ‘π‘™π‘’π‘‘π‘¦π‘π‘’β†’π‘‘π‘¦π‘π‘œπ‘›π‘‘π‘¦π‘£π‘Žπ‘Ÿ1β€¦π‘‘π‘¦π‘£π‘Žπ‘Ÿπ‘˜(π‘˜β‰₯0)

A type synonym declaration introduces a new type that is equivalent to an old type. It has the form

πšπš’πš™πšŽπ‘‡π‘’1β€¦π‘’π‘˜=𝑑

which introduces a new type constructor, 𝑇. The type (𝑇𝑒1β€¦π‘’π‘˜) is equivalent to the type 𝑑[𝑑1/𝑒1,…,π‘‘π‘˜/π‘’π‘˜]. The type variables 𝑒1 through π‘’π‘˜ must be distinct and are scoped only over 𝑑; it is a static error for any other type variable to appear in 𝑑. The kind of the new type constructor 𝑇 is of the form πœ…1β†’β€¦β†’πœ…π‘˜β†’πœ… where the kinds πœ…π‘– of the arguments 𝑒𝑖 and πœ… of the right hand side 𝑑 are determined by kind inference as described in SectionΒ 4.6. For example, the following definition can be used to provide an alternative way of writing the list type constructor:

type List = []

Type constructor symbols 𝑇 introduced by type synonym declarations cannot be partially applied; it is a static error to use 𝑇 without the full number of arguments.

Although recursive and mutually recursive datatypes are allowed, this is not so for type synonyms, unless an algebraic datatype intervenes. For example,

  type Rec a   =  [Circ a]
  data Circ a  =  Tag [Rec a]

is allowed, whereas

  type Rec a   =  [Circ a]        -- invalid
  type Circ a  =  [Rec a]         -- invalid

is not. Similarly, type Rec a = [Rec a] is not allowed.

Type synonyms are a convenient, but strictly syntactic, mechanism to make type signatures more readable. A synonym and its definition are completely interchangeable, except in the instance type of an instance declaration (SectionΒ 4.3.2).

4.2.3 Datatype Renamings

π‘‘π‘œπ‘π‘‘π‘’π‘π‘™β†’πš—πšŽπš πšπš’πš™πšŽ[π‘π‘œπ‘›π‘‘π‘’π‘₯𝑑=>]π‘ π‘–π‘šπ‘π‘™π‘’π‘‘π‘¦π‘π‘’=π‘›π‘’π‘€π‘π‘œπ‘›π‘ π‘‘π‘Ÿ[π‘‘π‘’π‘Ÿπ‘–π‘£π‘–π‘›π‘”]
π‘›π‘’π‘€π‘π‘œπ‘›π‘ π‘‘π‘Ÿβ†’π‘π‘œπ‘›π‘Žπ‘‘π‘¦π‘π‘’
|π‘π‘œπ‘›{π‘£π‘Žπ‘Ÿ::𝑑𝑦𝑝𝑒}
π‘ π‘–π‘šπ‘π‘™π‘’π‘‘π‘¦π‘π‘’β†’π‘‘π‘¦π‘π‘œπ‘›π‘‘π‘¦π‘£π‘Žπ‘Ÿ1β€¦π‘‘π‘¦π‘£π‘Žπ‘Ÿπ‘˜(π‘˜β‰₯0)

A declaration of the form

πš—πšŽπš πšπš’πš™πšŽπ‘π‘₯=>𝑇𝑒1β€¦π‘’π‘˜=𝑁 𝑑

introduces a new type whose representation is the same as an existing type. The type (𝑇𝑒1β€¦π‘’π‘˜) renames the datatype 𝑑. It differs from a type synonym in that it creates a distinct type that must be explicitly coerced to or from the original type. Also, unlike type synonyms, newtype may be used to define recursive types. The constructor 𝑁 in an expression coerces a value from type t to type (𝑇𝑒1β€¦π‘’π‘˜). Using 𝑁 in a pattern coerces a value from type (𝑇𝑒1β€¦π‘’π‘˜) to type 𝑑. These coercions may be implemented without execution time overhead; newtype does not change the underlying representation of an object.

New instances (see SectionΒ 4.3.2) can be defined for a type defined by newtype but may not be defined for a type synonym. A type created by newtype differs from an algebraic datatype in that the representation of an algebraic datatype has an extra level of indirection. This difference may make access to the representation less efficient. The difference is reflected in different rules for pattern matching (see SectionΒ 3.17). Unlike algebraic datatypes, the newtype constructor 𝑁 is unlifted, so that 𝑁 βŠ₯ is the same as βŠ₯.

The following examples clarify the differences between data (algebraic datatypes), type (type synonyms), and newtype (renaming types.) Given the declarations

  data D1 = D1 Int
  data D2 = D2 !Int
  type S = Int
  newtype N = N Int
  d1 (D1 i) = 42
  d2 (D2 i) = 42
  s i = 42
  n (N i) = 42

the expressions (𝚍𝟷 βŠ₯), (𝚍𝟸 βŠ₯) and (𝚍𝟸(π™³πŸΈ βŠ₯)) are all equivalent to βŠ₯, whereas (πš—βŠ₯), (πš—(𝙽βŠ₯)), (𝚍𝟷(π™³πŸ· βŠ₯)) and (𝚜βŠ₯) are all equivalent to 42. In particular, (𝙽βŠ₯) is equivalent to βŠ₯ while (π™³πŸ· βŠ₯) is not equivalent to βŠ₯.

The optional deriving part of a deriving declaration is treated in the same way as the deriving component of a data declaration; see SectionΒ 4.3.3.

A newtype declaration may use field-naming syntax, though of course there may only be one field. Thus:

  newtype Age = Age { unAge :: Int }

brings into scope both a constructor and a de-constructor:

  Age   :: Int -> Age
  unAge :: Age -> Int

4.3 Type Classes and Overloading

4.3.1 Class Declarations

π‘‘π‘œπ‘π‘‘π‘’π‘π‘™β†’πšŒπš•πšŠπšœπšœ[π‘ π‘π‘œπ‘›π‘‘π‘’π‘₯𝑑=>]π‘‘π‘¦π‘π‘™π‘ π‘‘π‘¦π‘£π‘Žπ‘Ÿ[πš πš‘πšŽπš›πšŽπ‘π‘‘π‘’π‘π‘™π‘ ]
π‘ π‘π‘œπ‘›π‘‘π‘’π‘₯π‘‘β†’π‘ π‘–π‘šπ‘π‘™π‘’π‘π‘™π‘Žπ‘ π‘ 
|(π‘ π‘–π‘šπ‘π‘™π‘’π‘π‘™π‘Žπ‘ π‘ 1,…,π‘ π‘–π‘šπ‘π‘™π‘’π‘π‘™π‘Žπ‘ π‘ π‘›)(𝑛β‰₯0)
π‘ π‘–π‘šπ‘π‘™π‘’π‘π‘™π‘Žπ‘ π‘ β†’π‘žπ‘‘π‘¦π‘π‘™π‘ π‘‘π‘¦π‘£π‘Žπ‘Ÿ
𝑐𝑑𝑒𝑐𝑙𝑠→{𝑐𝑑𝑒𝑐𝑙1;…;𝑐𝑑𝑒𝑐𝑙𝑛}(𝑛β‰₯0)
𝑐𝑑𝑒𝑐𝑙→𝑔𝑒𝑛𝑑𝑒𝑐𝑙
|(π‘“π‘’π‘›π‘™β„Žπ‘ |π‘£π‘Žπ‘Ÿ)π‘Ÿβ„Žπ‘ 

A class declaration introduces a new class and the operations (class methods) on it. A class declaration has the general form:

πšŒπš•πšŠπšœπšœπ‘π‘₯=>πΆπ‘’πš πš‘πšŽπš›πšŽπ‘π‘‘π‘’π‘π‘™π‘ 

This introduces a new class name 𝐢; the type variable 𝑒 is scoped only over the class method signatures in the class body. The context 𝑐π‘₯ specifies the superclasses of 𝐢, as described below; the only type variable that may be referred to in 𝑐π‘₯ is 𝑒.

The superclass relation must not be cyclic; i.e.Β it must form a directed acyclic graph.

The 𝑐𝑑𝑒𝑐𝑙𝑠 part of a class declaration contains three kinds of declarations:

Other than these cases, no other declarations are permitted in 𝑐𝑑𝑒𝑐𝑙𝑠.

A class declaration with no where part may be useful for combining a collection of classes into a larger one that inherits all of the class methods in the original ones. For example:

  class  (Read a, Show a) => Textual a

In such a case, if a type is an instance of all superclasses, it is not automatically an instance of the subclass, even though the subclass has no immediate class methods. The instance declaration must be given explicitly with no where part.

4.3.2 Instance Declarations

π‘‘π‘œπ‘π‘‘π‘’π‘π‘™β†’πš’πš—πšœπšπšŠπš—πšŒπšŽ[π‘ π‘π‘œπ‘›π‘‘π‘’π‘₯𝑑=>]π‘žπ‘‘π‘¦π‘π‘™π‘ π‘–π‘›π‘ π‘‘[πš πš‘πšŽπš›πšŽπ‘–π‘‘π‘’π‘π‘™π‘ ]
π‘–π‘›π‘ π‘‘β†’π‘”π‘‘π‘¦π‘π‘œπ‘›
|(π‘”π‘‘π‘¦π‘π‘œπ‘›π‘‘π‘¦π‘£π‘Žπ‘Ÿ1β€¦π‘‘π‘¦π‘£π‘Žπ‘Ÿπ‘˜)(π‘˜β‰₯0, π‘‘π‘¦π‘£π‘Žπ‘Ÿπ‘  distinct)
|(π‘‘π‘¦π‘£π‘Žπ‘Ÿ1,…,π‘‘π‘¦π‘£π‘Žπ‘Ÿπ‘˜)(π‘˜β‰₯2, π‘‘π‘¦π‘£π‘Žπ‘Ÿπ‘  distinct)
|[π‘‘π‘¦π‘£π‘Žπ‘Ÿ]
|(π‘‘π‘¦π‘£π‘Žπ‘Ÿ1->π‘‘π‘¦π‘£π‘Žπ‘Ÿ2)(π‘‘π‘¦π‘£π‘Žπ‘Ÿ1 and π‘‘π‘¦π‘£π‘Žπ‘Ÿ2 distinct)
𝑖𝑑𝑒𝑐𝑙𝑠→{𝑖𝑑𝑒𝑐𝑙1;…;𝑖𝑑𝑒𝑐𝑙𝑛}(𝑛β‰₯0)
𝑖𝑑𝑒𝑐𝑙→(π‘“π‘’π‘›π‘™β„Žπ‘ |π‘£π‘Žπ‘Ÿ)π‘Ÿβ„Žπ‘ 
|(empty)

An instance declaration introduces an instance of a class. Let

πšŒπš•πšŠπšœπšœπ‘π‘₯=>𝐢 π‘’πš πš‘πšŽπš›πšŽ{π‘π‘π‘œπ‘‘π‘¦}

be a class declaration. The general form of the corresponding instance declaration is:

πš’πš—πšœπšπšŠπš—πšŒπšŽπ‘π‘₯β€²=>𝐢 (𝑇 𝑒1β€¦π‘’π‘˜)πš πš‘πšŽπš›πšŽ{𝑑}

where π‘˜β‰₯0. The type (𝑇𝑒1β€¦π‘’π‘˜) must take the form of a type constructor 𝑇 applied to simple type variables 𝑒1,…,π‘’π‘˜; furthermore, 𝑇 must not be a type synonym, and the 𝑒𝑖 must all be distinct.

This prohibits instance declarations such as:

  instance C (a,a) where ...
  instance C (Int,a) where ...
  instance C [[a]] where ...

The declarations 𝑑 may contain bindings only for the class methods of 𝐢. It is illegal to give a binding for a class method that is not in scope, but the name under which it is in scope is immaterial; in particular, it may be a qualified name. (This rule is identical to that used for subordinate names in export lists β€” SectionΒ 5.2.) For example, this is legal, even though range is in scope only with the qualified name Data.Ix.range.

  module A where
    import qualified Data.Ix

    instance Data.Ix.Ix T where
      range = ...

The declarations may not contain any type signatures or fixity declarations, since these have already been given in the class declaration. As in the case of default class methods (SectionΒ 4.3.1), the method declarations must take the form of a variable or function definition.

If no binding is given for some class method then the corresponding default class method in the class declaration is used (if present); if such a default does not exist then the class method of this instance is bound to undefined and no compile-time error results.

An instance declaration that makes the type 𝑇 to be an instance of class 𝐢 is called a C-T instance declaration and is subject to these static restrictions:

The following example illustrates the restrictions imposed by superclass instances:

  class Foo a => Bar a where ...
  
  instance (Eq a, Show a) => Foo [a] where ...
  
  instance Num a => Bar [a] where ...

This example is valid Haskell. Since Foo is a superclass of Bar, the second instance declaration is only valid if [a] is an instance of Foo under the assumption Num a. The first instance declaration does indeed say that [a] is an instance of Foo under this assumption, because Eq and Show are superclasses of Num.

If the two instance declarations instead read like this:

  instance Num a => Foo [a] where ...
  
  instance (Eq a, Show a) => Bar [a] where ...

then the program would be invalid. The second instance declaration is valid only if [a] is an instance of Foo under the assumptions (Eq a, Show a). But this does not hold, since [a] is only an instance of Foo under the stronger assumption Num a.

Further examples of instance declarations may be found in ChapterΒ 9.

4.3.3 Derived Instances

As mentioned in SectionΒ 4.2.1, data and newtype declarations contain an optional deriving form. If the form is included, then derived instance declarations are automatically generated for the datatype in each of the named classes. These instances are subject to the same restrictions as user-defined instances. When deriving a class 𝐢 for a type 𝑇, instances for all superclasses of 𝐢 must exist for 𝑇, either via an explicit instance declaration or by including the superclass in the deriving clause.

Derived instances provide convenient commonly-used operations for user-defined datatypes. For example, derived instances for datatypes in the class Eq define the operations == and /=, freeing the programmer from the need to define them.

The only classes in the Prelude for which derived instances are allowed are Eq, Ord, Enum, Bounded, Show, and Read, all mentioned in FigureΒ 3. The precise details of how the derived instances are generated for each of these classes are provided in ChapterΒ 11, including a specification of when such derived instances are possible. Classes defined by the standard libraries may also be derivable.

A static error results if it is not possible to derive an instance declaration over a class named in a deriving form. For example, not all datatypes can properly support class methods in Enum. It is also a static error to give an explicit instance declaration for a class that is also derived.

If the deriving form is omitted from a data or newtype declaration, then no instance declarations are derived for that datatype; that is, omitting a deriving form is equivalent to including an empty deriving form: deriving ().

4.3.4 Ambiguous Types, and Defaults for Overloaded Numeric Operations

π‘‘π‘œπ‘π‘‘π‘’π‘π‘™β†’πšπšŽπšπšŠπšžπš•πš(𝑑𝑦𝑝𝑒1,…,𝑑𝑦𝑝𝑒𝑛)(𝑛β‰₯0)

A problem inherent with Haskell-style overloading is the possibility of an ambiguous type. For example, using the read and show functions defined in ChapterΒ 11, and supposing that just Int and Bool are members of Read and Show, then the expression

  let x = read "..." in show x  -- invalid

is ambiguous, because the types for show and read,

πšœπš‘πš˜πš  :: βˆ€π‘Ž.πš‚πš‘πš˜πš π‘Žβ‡’π‘Žβ†’πš‚πšπš›πš’πš—πšπš›πšŽπšŠπš :: βˆ€π‘Ž.πšπšŽπšŠπšπ‘Žβ‡’πš‚πšπš›πš’πš—πšβ†’π‘Ž

could be satisfied by instantiating a as either Int in both cases, or Bool. Such expressions are considered ill-typed, a static error.

We say that an expression e has an ambiguous type if, in its type βˆ€π‘’_.𝑐π‘₯⇒𝑑, there is a type variable 𝑒 in 𝑒_ that occurs in 𝑐π‘₯ but not in 𝑑. Such types are invalid.

For example, the earlier expression involving show and read has an ambiguous type since its type is βˆ€π‘Ž.πš‚πš‘πš˜πš π‘Ž,πšπšŽπšŠπšπ‘Žβ‡’πš‚πšπš›πš’πš—πš.

Ambiguous types can only be circumvented by input from the user. One way is through the use of expression type-signatures as described in SectionΒ 3.16. For example, for the ambiguous expression given earlier, one could write:

  let x = read "..." in show (x::Bool)

which disambiguates the type.

Occasionally, an otherwise ambiguous expression needs to be made the same type as some variable, rather than being given a fixed type with an expression type-signature. This is the purpose of the function asTypeOf (ChapterΒ 9): x `asTypeOf` y has the value of π‘₯, but π‘₯ and 𝑦 are forced to have the same type. For example,

  approxSqrt x = encodeFloat 1 (exponent x `div` 2) `asTypeOf` x

(See SectionΒ 6.4.6 for a description of encodeFloat and exponent.)

Ambiguities in the class Num are most common, so Haskell provides another way to resolve themβ€”with a default declaration:

πšπšŽπšπšŠπšžπš•πš(𝑑1,…,𝑑𝑛)

where 𝑛β‰₯0, and each 𝑑𝑖 must be a type for which π™½πšžπš–π‘‘π‘– holds. In situations where an ambiguous type is discovered, an ambiguous type variable, 𝑣, is defaultable if:

Each defaultable variable is replaced by the first type in the default list that is an instance of all the ambiguous variable’s classes. It is a static error if no such type is found.

Only one default declaration is permitted per module, and its effect is limited to that module. If no default declaration is given in a module then it assumed to be:

  default (Integer, Double)

The empty default declaration, default (), turns off all defaults in a module.

4.4 Nested Declarations

The following declarations may be used in any declaration list, including the top level of a module.

4.4.1 Type Signatures

π‘”π‘’π‘›π‘‘π‘’π‘π‘™β†’π‘£π‘Žπ‘Ÿπ‘ ::[π‘π‘œπ‘›π‘‘π‘’π‘₯𝑑=>]𝑑𝑦𝑝𝑒
π‘£π‘Žπ‘Ÿπ‘ β†’π‘£π‘Žπ‘Ÿ1,…,π‘£π‘Žπ‘Ÿπ‘›(𝑛β‰₯1)

A type signature specifies types for variables, possibly with respect to a context. A type signature has the form:

𝑣1,…,𝑣𝑛::𝑐π‘₯=>𝑑

which is equivalent to asserting 𝑣𝑖::𝑐π‘₯=>𝑑 for each 𝑖 from 1 to 𝑛. Each 𝑣𝑖 must have a value binding in the same declaration list that contains the type signature; i.e. it is invalid to give a type signature for a variable bound in an outer scope. Moreover, it is invalid to give more than one type signature for one variable, even if the signatures are identical.

As mentioned in SectionΒ 4.1.2, every type variable appearing in a signature is universally quantified over that signature, and hence the scope of a type variable is limited to the type signature that contains it. For example, in the following declarations

f :: a -> a
f x = x :: a                  -- invalid

the a’s in the two type signatures are quite distinct. Indeed, these declarations contain a static error, since x does not have type βˆ€π‘Ž.π‘Ž. (The type of x is dependent on the type of f; there is currently no way in Haskell to specify a signature for a variable with a dependent type; this is explained in SectionΒ 4.5.4.)

If a given program includes a signature for a variable 𝑓, then each use of 𝑓 is treated as having the declared type. It is a static error if the same type cannot also be inferred for the defining occurrence of 𝑓.

If a variable 𝑓 is defined without providing a corresponding type signature declaration, then each use of 𝑓 outside its own declaration group (see SectionΒ 4.5.1) is treated as having the corresponding inferred, or principal type. However, to ensure that type inference is still possible, the defining occurrence, and all uses of 𝑓 within its declaration group must have the same monomorphic type (from which the principal type is obtained by generalization, as described in SectionΒ 4.5.2).

For example, if we define

sqr x  =  x*x

then the principal type is πšœπššπš›::βˆ€π‘Ž.π™½πšžπš–π‘Žβ‡’π‘Žβ†’π‘Ž, which allows applications such as sqr 5 or sqr 0.1. It is also valid to declare a more specific type, such as

sqr :: Int -> Int

but now applications such as sqr 0.1 are invalid. Type signatures such as

sqr :: (Num a, Num b) => a -> b     -- invalid
sqr :: a -> a                       -- invalid

are invalid, as they are more general than the principal type of sqr.

Type signatures can also be used to support polymorphic recursion. The following definition is pathological, but illustrates how a type signature can be used to specify a type more general than the one that would be inferred:

data T a  =  K (T Int) (T a)
f         :: T a -> a
f (K x y) =  if f x == 1 then f y else undefined

If we remove the signature declaration, the type of f will be inferred as T Int -> Int due to the first recursive call for which the argument to f is T Int. Polymorphic recursion allows the user to supply the more general type signature, T a -> a.

4.4.2 Fixity Declarations

𝑔𝑒𝑛𝑑𝑒𝑐𝑙→𝑓𝑖π‘₯𝑖𝑑𝑦[π‘–π‘›π‘‘π‘’π‘”π‘’π‘Ÿ]π‘œπ‘π‘ 
𝑓𝑖π‘₯π‘–π‘‘π‘¦β†’πš’πš—πšπš’πš‘πš•|πš’πš—πšπš’πš‘πš›|πš’πš—πšπš’πš‘
π‘œπ‘π‘ β†’π‘œπ‘1,…,π‘œπ‘π‘›(𝑛β‰₯1)
π‘œπ‘β†’π‘£π‘Žπ‘Ÿπ‘œπ‘|π‘π‘œπ‘›π‘œπ‘

A fixity declaration gives the fixity and binding precedence of one or more operators. The π‘–π‘›π‘‘π‘’π‘”π‘’π‘Ÿ in a fixity declaration must be in the range 0 to 9. A fixity declaration may appear anywhere that a type signature appears and, like a type signature, declares a property of a particular operator. Also like a type signature, a fixity declaration can only occur in the same sequence of declarations as the declaration of the operator itself, and at most one fixity declaration may be given for any operator. (Class methods are a minor exception; their fixity declarations can occur either in the class declaration itself or at top level.)

There are three kinds of fixity, non-, left- and right-associativity (infix, infixl, and infixr, respectively), and ten precedence levels, 0 to 9 inclusive (level 0 binds least tightly, and level 9 binds most tightly). If the 𝑑𝑖𝑔𝑖𝑑 is omitted, level 9 is assumed. Any operator lacking a fixity declaration is assumed to be infixl 9 (See ChapterΒ 3 for more on the use of fixities). TableΒ 1 lists the fixities and precedences of the operators defined in the Prelude.

PrecedenceLeft associative operatorsNon-associative operatorsRight associative operators
9!!.
8^,^^,**
7*, /, div, mod, rem, quot
6+,-
5:,++
4==, /=, <,<=, >, >=, elem, notElem
3&&
2||
1>>, >>=
0$, $!, seq
TableΒ 1: Precedences and fixities of prelude operators

Fixity is a property of a particular entity (constructor or variable), just like its type; fixity is not a property of that entity’s name. For example:

  module Bar( op ) where
    infixr 7 `op`
    op = ...
  
  module Foo where
    import qualified Bar
    infix 3 `op`
  
    a `op` b = (a `Bar.op` b) + 1
  
    f x = let
             p `op` q = (p `Foo.op` q) * 2
          in ...

Here, `Bar.op` is infixr 7, `Foo.op` is infix 3, and the nested definition of op in f’s right-hand side has the default fixity of infixl 9. (It would also be possible to give a fixity to the nested definition of `op` with a nested fixity declaration.)

4.4.3 Function and Pattern Bindings

𝑑𝑒𝑐𝑙→(π‘“π‘’π‘›π‘™β„Žπ‘ |π‘π‘Žπ‘‘)π‘Ÿβ„Žπ‘ 
π‘“π‘’π‘›π‘™β„Žπ‘ β†’π‘£π‘Žπ‘Ÿπ‘Žπ‘π‘Žπ‘‘{π‘Žπ‘π‘Žπ‘‘}
|π‘π‘Žπ‘‘π‘£π‘Žπ‘Ÿπ‘œπ‘π‘π‘Žπ‘‘
|(π‘“π‘’π‘›π‘™β„Žπ‘ )π‘Žπ‘π‘Žπ‘‘{π‘Žπ‘π‘Žπ‘‘}
π‘Ÿβ„Žπ‘ β†’=𝑒π‘₯𝑝[πš πš‘πšŽπš›πšŽπ‘‘π‘’π‘π‘™π‘ ]
|π‘”π‘‘π‘Ÿβ„Žπ‘ [πš πš‘πšŽπš›πšŽπ‘‘π‘’π‘π‘™π‘ ]
π‘”π‘‘π‘Ÿβ„Žπ‘ β†’π‘”π‘’π‘Žπ‘Ÿπ‘‘π‘ =𝑒π‘₯𝑝[π‘”π‘‘π‘Ÿβ„Žπ‘ ]
π‘”π‘’π‘Žπ‘Ÿπ‘‘π‘ β†’|π‘”π‘’π‘Žπ‘Ÿπ‘‘1,…,π‘”π‘’π‘Žπ‘Ÿπ‘‘π‘›(𝑛β‰₯1)
π‘”π‘’π‘Žπ‘Ÿπ‘‘β†’π‘π‘Žπ‘‘<-𝑖𝑛𝑓𝑖π‘₯𝑒π‘₯𝑝(pattern guard)
|πš•πšŽπšπ‘‘π‘’π‘π‘™π‘ (local declaration)
|𝑖𝑛𝑓𝑖π‘₯𝑒π‘₯𝑝(boolean guard)

We distinguish two cases within this syntax: a pattern binding occurs when the left hand side is a π‘π‘Žπ‘‘; otherwise, the binding is called a function binding. Either binding may appear at the top-level of a module or within a where or let construct.

4.4.3.1 Function bindings

A function binding binds a variable to a function value. The general form of a function binding for variable π‘₯ is:

π‘₯𝑝11 … 𝑝1π‘˜π‘šπ‘Žπ‘‘π‘β„Ž1
…
π‘₯𝑝𝑛1 … π‘π‘›π‘˜π‘šπ‘Žπ‘‘π‘β„Žπ‘›

where each 𝑝𝑖𝑗 is a pattern, and where each π‘šπ‘Žπ‘‘π‘β„Žπ‘– is of the general form:

=π‘’π‘–πš πš‘πšŽπš›πšŽ{ 𝑑𝑒𝑐𝑙𝑠𝑖 }

or

|𝑔𝑠𝑖1=𝑒𝑖1
…
|π‘”π‘ π‘–π‘šπ‘–=π‘’π‘–π‘šπ‘–
πš πš‘πšŽπš›πšŽ{ 𝑑𝑒𝑐𝑙𝑠𝑖 }

and where 𝑛β‰₯1, 1≀𝑖≀𝑛, π‘šπ‘–β‰₯1. The former is treated as shorthand for a particular case of the latter, namely:

|πšƒπš›πšžπšŽ=π‘’π‘–πš πš‘πšŽπš›πšŽ{ 𝑑𝑒𝑐𝑙𝑠𝑖 }

Note that all clauses defining a function must be contiguous, and the number of patterns in each clause must be the same. The set of patterns corresponding to each match must be linearβ€”no variable is allowed to appear more than once in the entire set.

Alternative syntax is provided for binding functional values to infix operators. For example, these three function definitions are all equivalent:

plus x y z = x+y+z
x `plus` y = \ z -> x+y+z
(x `plus` y) z = x+y+z

Note that fixity resolution applies to the infix variants of the function binding in the same way as for expressions (SectionΒ 10.6). Applying fixity resolution to the left side of the equals in a function binding must leave the π‘£π‘Žπ‘Ÿπ‘œπ‘ being defined at the top level. For example, if we are defining a new operator ## with precedence 6, then this definition would be illegal:

  a ## b : xs = exp

because : has precedence 5, so the left hand side resolves to (a ## x) : xs, and this cannot be a pattern binding because (a ## x) is not a valid pattern.

Translation: The general binding form for functions is semantically equivalent to the equation (i.e. simple pattern binding):

π‘₯=\π‘₯1…π‘₯π‘˜-> 𝚌𝚊𝚜𝚎(π‘₯1,…,π‘₯π‘˜)𝚘𝚏(𝑝11,…,𝑝1π‘˜) π‘šπ‘Žπ‘‘π‘β„Ž1
…
(𝑝𝑛1,…,π‘π‘›π‘˜) π‘šπ‘Žπ‘‘π‘β„Žπ‘›

where the π‘₯𝑖 are new identifiers.

4.4.3.2 Pattern bindings

A pattern binding binds variables to values. A simple pattern binding has form 𝑝=𝑒. The pattern 𝑝 is matched β€œlazily” as an irrefutable pattern, as if there were an implicit ~ in front of it. See the translation in Section SectionΒ 3.12.

The general form of a pattern binding is π‘π‘šπ‘Žπ‘‘π‘β„Ž, where a π‘šπ‘Žπ‘‘π‘β„Ž is the same structure as for function bindings above; in other words, a pattern binding is:

𝑝|𝑔𝑠1=𝑒1
|𝑔𝑠2=𝑒2
…
|π‘”π‘ π‘š=π‘’π‘š
πš πš‘πšŽπš›πšŽ{ 𝑑𝑒𝑐𝑙𝑠 }

Translation: The pattern binding above is semantically equivalent to this simple pattern binding:

𝑝 =πš•πšŽπšπ‘‘π‘’π‘π‘™π‘ πš’πš—
𝚌𝚊𝚜𝚎()𝚘𝚏
()|𝑔𝑠1→𝑒1
|𝑔𝑠2→𝑒2
…
|π‘”π‘ π‘šβ†’π‘’π‘š
_β†’πšŽπš›πš›πš˜πš› "πš„πš—πš–πšŠπšπšŒπš‘πšŽπš πš™πšŠπšπšπšŽπš›πš—"

4.5 Static Semantics of Function and Pattern Bindings

The static semantics of the function and pattern bindings of a let expression or where clause are discussed in this section.

4.5.1 Dependency Analysis

In general the static semantics are given by applying the normal Hindley-Milner inference rules. In order to increase polymorphism, these rules are applied to groups of bindings identified by a dependency analysis.

A binding 𝑏1 depends on a binding 𝑏2 in the same list of declarations if either

  1. 𝑏1 contains a free identifier that has no type signature and is bound by 𝑏2, or
  2. 𝑏1 depends on a binding that depends on 𝑏2.

A declaration group is a minimal set of mutually dependent bindings. Hindley-Milner type inference is applied to each declaration group in dependency order. The order of declarations in where/let constructs is irrelevant.

4.5.2 Generalization

The Hindley-Milner type system assigns types to a let-expression in two stages:

  1. The declaration groups are considered in dependency order. For each group, a type with no universal quantification is inferred for each variable bound in the group. Then, all type variables that occur in these types are universally quantified unless they are associated with bound variables in the type environment; this is called generalization.
  2. Finally, the body of the let-expression is typed.

For example, consider the declaration

  f x = let g y = (y,y)
        in ...

The type of g’s definition is π‘Žβ†’(π‘Ž,π‘Ž). The generalization step attributes to g the polymorphic type βˆ€π‘Ž.π‘Žβ†’(π‘Ž,π‘Ž), after which the typing of the β€œ...” part can proceed.

When typing overloaded definitions, all the overloading constraints from a single declaration group are collected together, to form the context for the type of each variable declared in the group. For example, in the definition:

  f x = let g1 x y = if x>y then show x else g2 y x
            g2 p q = g1 q p
        in ...

The types of the definitions of g1 and g2 are both π‘Žβ†’π‘Žβ†’πš‚πšπš›πš’πš—πš, and the accumulated constraints are π™Ύπš›πšπ‘Ž (arising from the use of >), and πš‚πš‘πš˜πš π‘Ž (arising from the use of show). The type variables appearing in this collection of constraints are called the constrained type variables.

The generalization step attributes to both g1 and g2 the type

βˆ€π‘Ž.(π™Ύπš›πšπ‘Ž,πš‚πš‘πš˜πš π‘Ž)β‡’π‘Žβ†’π‘Žβ†’πš‚πšπš›πš’πš—πš

Notice that g2 is overloaded in the same way as g1 even though the occurrences of > and show are in the definition of g1.

If the programmer supplies explicit type signatures for more than one variable in a declaration group, the contexts of these signatures must be identical up to renaming of the type variables.

4.5.3 Context Reduction Errors

As mentioned in SectionΒ 4.1.4, the context of a type may constrain only a type variable, or the application of a type variable to one or more types. Hence, types produced by generalization must be expressed in a form in which all context constraints have be reduced to this β€œhead normal form”. Consider, for example, the definition:

  f xs y  =  xs == [y]

Its type is given by

  f :: Eq a => [a] -> a -> Bool

and not

  f :: Eq [a] => [a] -> a -> Bool

Even though the equality is taken at the list type, the context must be simplified, using the instance declaration for Eq on lists, before generalization. If no such instance is in scope, a static error occurs.

Here is an example that shows the need for a constraint of the form 𝐢(π‘š 𝑑) where m is one of the type variables being generalized; that is, where the class 𝐢 applies to a type expression that is not a type variable or a type constructor. Consider:

  f :: (Monad m, Eq (m a)) => a -> m a -> Bool
  f x y = return x == y

The type of return is Monad m => a -> m a; the type of (==) is Eq a => a -> a -> Bool. The type of f should be therefore (Monad m, Eq (m a)) => a -> m a -> Bool, and the context cannot be simplified further.

The instance declaration derived from a data type deriving clause (see SectionΒ 4.3.3) must, like any instance declaration, have a simple context; that is, all the constraints must be of the form 𝐢 π‘Ž, where π‘Ž is a type variable. For example, in the type

  data Apply a b = App (a b)  deriving Show

the derived Show instance will produce a context Show (a b), which cannot be reduced and is not simple; thus a static error results.

4.5.4 Monomorphism

Sometimes it is not possible to generalize over all the type variables used in the type of the definition. For example, consider the declaration

  f x = let g y z = ([x,y], z)
        in ...

In an environment where x has type π‘Ž, the type of g’s definition is π‘Žβ†’π‘β†’([π‘Ž],𝑏). The generalization step attributes to mbox{tt g} the type βˆ€π‘.π‘Žβ†’π‘β†’([π‘Ž],𝑏); only 𝑏 can be universally quantified because π‘Ž occurs in the type environment. We say that the type of g is monomorphic in the type variable π‘Ž.

The effect of such monomorphism is that the first argument of all applications of g must be of a single type. For example, it would be valid for the β€œ...” to be

  (g True, g False)

(which would, incidentally, force x to have type Bool) but invalid for it to be

  (g True, g 'c')

In general, a type βˆ€π‘’_.𝑐π‘₯⇒𝑑 is said to be monomorphic in the type variable π‘Ž if π‘Ž is free in βˆ€π‘’_.𝑐π‘₯⇒𝑑.

It is worth noting that the explicit type signatures provided by Haskell are not powerful enough to express types that include monomorphic type variables. For example, we cannot write

  f x = let 
          g :: a -> b -> ([a],b)
          g y z = ([x,y], z)
        in ...

because that would claim that g was polymorphic in both a and b (SectionΒ 4.4.1). In this program, g can only be given a type signature if its first argument is restricted to a type not involving type variables; for example

  g :: Int -> b -> ([Int],b)

This signature would also cause x to have type Int.

4.5.5 The Monomorphism Restriction

Haskell places certain extra restrictions on the generalization step, beyond the standard Hindley-Milner restriction described above, which further reduces polymorphism in particular cases.

The monomorphism restriction depends on the binding syntax of a variable. Recall that a variable is bound by either a function binding or a pattern binding, and that a simple pattern binding is a pattern binding in which the pattern consists of only a single variable (SectionΒ 4.4.3).

The following two rules define the monomorphism restriction:

The monomorphism restriction

Rule 1.

We say that a given declaration group is unrestricted if and only if:

(a)
every variable in the group is bound by a function binding or a simple pattern binding (SectionΒ 4.4.3.2), and
(b)
an explicit type signature is given for every variable in the group that is bound by simple pattern binding.

The usual Hindley-Milner restriction on polymorphism is that only type variables that do not occur free in the environment may be generalized. In addition, the constrained type variables of a restricted declaration group may not be generalized in the generalization step for that group. (Recall that a type variable is constrained if it must belong to some type class; see SectionΒ 4.5.2.)

Rule 2.
Any monomorphic type variables that remain when type inference for an entire module is complete, are considered ambiguous, and are resolved to particular types using the defaulting rules (SectionΒ 4.3.4).

Motivation Rule 1 is required for two reasons, both of which are fairly subtle.

RuleΒ 2 is required because there is no way to enforce monomorphic use of an exported binding, except by performing type inference on modules outside the current module. RuleΒ 2 states that the exact types of all the variables bound in a module must be determined by that module alone, and not by any modules that import it.

  module M1(len1) where
    default( Int, Double )
    len1 = genericLength "Hello"

  module M2 where
    import M1(len1)
    len2 = (2*len1) :: Rational

When type inference on module M1 is complete, len1 has the monomorphic type Num a => a (by Rule 1). Rule 2 now states that the monomorphic type variable a is ambiguous, and must be resolved using the defaulting rules of SectionΒ 4.3.4. Hence, len1 gets type Int, and its use in len2 is type-incorrect. (If the above code is actually what is wanted, a type signature on len1 would solve the problem.)

This issue does not arise for nested bindings, because their entire scope is visible to the compiler.

Consequences The monomorphism rule has a number of consequences for the programmer. Anything defined with function syntax usually generalizes as a function is expected to. Thus in

  f x y = x+y

the function f may be used at any overloading in class Num. There is no danger of recomputation here. However, the same function defined with pattern syntax:

  f = \x -> \y -> x+y

requires a type signature if f is to be fully overloaded. Many functions are most naturally defined using simple pattern bindings; the user must be careful to affix these with type signatures to retain full overloading. The standard prelude contains many examples of this:

  sum  :: (Num a) => [a] -> a
  sum  =  foldl (+) 0  

RuleΒ 1 applies to both top-level and nested definitions. Consider

  module M where
    len1 = genericLength "Hello"
    len2 = (2*len1) :: Rational

Here, type inference finds that len1 has the monomorphic type (Num a => a); and the type variable a is resolved to Rational when performing type inference on len2.

4.6 Kind Inference

This section describes the rules that are used to perform kind inference, i.e. to calculate a suitable kind for each type constructor and class appearing in a given program.

The first step in the kind inference process is to arrange the set of datatype, synonym, and class definitions into dependency groups. This can be achieved in much the same way as the dependency analysis for value declarations that was described in SectionΒ 4.5.1. For example, the following program fragment includes the definition of a datatype constructor D, a synonym S and a class C, all of which would be included in the same dependency group:


  data C a => D a = Foo (S a)
  type S a = [D a]
  class C a where
      bar :: a -> D a -> Bool

The kinds of variables, constructors, and classes within each group are determined using standard techniques of type inference and kind-preserving unification [6]. For example, in the definitions above, the parameter a appears as an argument of the function constructor (->) in the type of bar and hence must have kind βˆ—. It follows that both D and S must have kind βˆ—β†’βˆ— and that every instance of class C must have kind βˆ—.

It is possible that some parts of an inferred kind may not be fully determined by the corresponding definitions; in such cases, a default of βˆ— is assumed. For example, we could assume an arbitrary kind πœ… for the a parameter in each of the following examples:

  data App f a = A (f a)
  data Tree a  = Leaf | Fork (Tree a) (Tree a)

This would give kinds (πœ…β†’βˆ—)β†’πœ…β†’βˆ— and πœ…β†’βˆ— for App and Tree, respectively, for any kind πœ…, and would require an extension to allow polymorphic kinds. Instead, using the default binding πœ…=βˆ—, the actual kinds for these two constructors are (βˆ—β†’βˆ—)β†’βˆ—β†’βˆ— and βˆ—β†’βˆ—, respectively.

Defaults are applied to each dependency group without consideration of the ways in which particular type constructor constants or classes are used in later dependency groups or elsewhere in the program. For example, adding the following definition to those above does not influence the kind inferred for Tree (by changing it to (βˆ—β†’βˆ—)β†’βˆ—, for instance), and instead generates a static error because the kind of [], βˆ—β†’βˆ—, does not match the kind βˆ— that is expected for an argument of Tree:

  type FunnyTree = Tree []     -- invalid

This is important because it ensures that each constructor and class are used consistently with the same kind whenever they are in scope.