5 Modules

A module defines a collection of values, datatypes, type synonyms, classes, etc. (see Section 4) in an environment created by a set of imports, resources brought into scope from other modules, and exports some of these resources, making them available to other modules. We use the term entity to refer to a value, type, or classes defined in, imported into, or perhaps exported from a module.

A Haskell program is a collection of modules, one of which, by convention, must be called Main and must export the value main. The value of the program is the value of the identifier main in module Main, and main must have type IO () (see Section 7).

Modules may reference other modules via explicit import declarations, each giving the name of a module to be imported and specifying its entities to be imported. Modules may be mutually recursive.

The name-space for modules is flat, with each module being associated with a unique module name (which are Haskell identifiers beginning with a capital letter; i.e. modid). There is one distinguished module, Prelude, which is imported into all programs by default (see Section 5.3), plus a set of standard library modules which may be imported as required (see the Haskell Library Report).

5.1 Module Structure

A module defines a mutually recursive scope containing declarations for value bindings, data types, type synonyms, classes, etc. (see Section 4).

module        -> module modid [exports] where body
              |  body
body          -> { [impdecls ;] [[fixdecls ;] topdecls [;]] }
              |  { impdecls [;] }

modid         -> conid
impdecls      -> impdecl1 ; ... ; impdecln                
topdecls      -> topdecl1 ; ... ; topdecln                

A module begins with a header: the keyword module, the module name, and a list of entities (enclosed in round parentheses) to be exported. The header is followed by an optional list of import declarations that specify modules to be imported, optionally restricting the imported bindings. This is followed by an optional list of fixity declarations and the module body. The module body is simply a list of top-level declarations (topdecls), as described in Section 4.

An abbreviated form of module is permitted which consists only of the module body. If this is used, the header is assumed to be `module Main(main) where'. If the first lexeme in the abbreviated module is not a {, then the layout rule applies for the top level of the module.

5.1.1 Export Lists

exports       -> ( export1 , ... , exportn [ , ] )        

export        -> qvar
              |  qtycon [(..) | ( qcname1 , ... , qcnamen )]     
              |  qtycls [(..) | ( qvar1 , ... , qvarn )]     
              |  module modid

qcname        -> qvar | qcon

An export list identifies the entities to be exported by a module declaration. A module implementation may only export an entity that it declares, or that it imports from some other module. If the export list is omitted, all values, types and classes defined in the module are exported, but not those that are imported.

Entities in an export list may be named as follows:

  1. Ordinary values, whether declared in the module body or imported, may be named by giving the name of the value as a qvarid. Operators should be enclosed in parentheses to turn them into qvarid's.
  2. An algebraic datatype T declared by a data or newtype declaration may be named in one of three ways: Data constructors and field names cannot be named in export lists in any other way.
  3. A type synonym T declared by a type declaration may be named by the form T.
  4. A class C with operations f1,...,fn declared in a class declaration may be named in one of three ways: Class methods may not be named in export lists in any other way.
  5. The set of all entities brought into scope from a module m by one or more unqualified import declarations may be named by the form `module m', which is equivalent to listing all of the entities imported from the module. For example:
    
          module Queue( module Stack, enqueue, dequeue ) where
              import Stack
              ...
    
    Here the module Queue uses the module name Stack in its export list to abbreviate all the entities imported from Stack.

  6. A module can name its own local definitions in its export list using its name in the `module m' syntax. For example:
    
           module Mod1(module Mod1, module Mod2) where
           import Mod2
           import Mod3
    
    Here module Mod1 exports all local definitions as well as those from imported from Mod2 but not those imported from Mod3.
The qualifier (Section 5.1.2) on a name only identifies the module an entity is imported from; this may be different from the module in which the entity is defined. For example, if module A exports B.c, this is referenced as `A.c', not `A.B.c'. In consequence, names in export lists must remain distinct after qualifiers are removed. For example:

module A ( B.f, C.f, g, B.g ) where   -- an invalid module
import qualified B(f,g)
import qualified C(f)
g = True
There are name clashes in the export list between B.f and C.f and between g and B.g even though there are no name clashes within module A.

5.1.2 Import Declarations

impdecl       -> import [qualified] modid [as modid] [impspec]
impspec       -> ( import1 , ... , importn [ , ] )        
              |  hiding ( import1 , ... , importn [ , ] )     

import        -> var
              |  tycon [ (..) | ( cname1 , ... , cnamen )]     
              |  tycls [(..) | ( var1 , ... , varn )]     
cname         -> var | con

The entities exported by a module may be brought into scope in another module with an import declaration at the beginning of the module. The import declaration names the module to be imported and optionally specifies the entities to be imported. A single module may be imported by more than one import declaration. Imported names serve as top level declarations: they scope over the entire body of the module but may be shadowed by local non-top-level bindings. The effect of multiple import declarations is cumulative: an entity is in scope if it named by any of the import declarations in a module. The ordering of imports is irrelevant.

Exactly which entities are to be imported can be specified in one of three ways:

  1. The imported entities can be specified explicitly by listing them in parentheses. Items in the list have the same form as those in export lists, except qualifiers are not permitted and the `module modid' entity is not permitted.

    The list must name only entities exported by the imported module. The list may be empty, in which case nothing except the instances are imported.

  2. Entities can be excluded by using the form hiding(import1 , ... , importn ), which specifies that all entities exported by the named module should be imported except for those named in the list. The effect of multiple import declarations is strictly cumulative: hiding an entity on one import declaration does not prevent the same entity from being imported by another import from the same module.

  3. Finally, if impspec is omitted then all the entities exported by the specified module are imported.

When an import declaration uses the qualified keyword, the names brought into scope must be prefixed by the name of the imported module (or a local alias, if an as clause is present). A qualified name is written as modid.name. This allows full programmer control of the unqualified namespace: a locally defined entity can share the same name as a qualified import:


module Ring where
import qualified Prelude  -- All Prelude names must be qualified

l1 + l2 = l1 ++ l2        -- This + differs from the one in the Prelude
l1 * l2 = nub (l1 + l2)

succ = (Prelude.+ 1)
The qualifier does not change the syntactic treatment of a name: Prelude.+ is an infix operator with the same fixity as the definition of + in the Prelude. Qualifiers may be applied to names imported by an unqualified import; this allows a qualified import to be replaced with an unqualified one without forcing changes in the references to the imported names.

Imported modules may be assigned a local alias in the importing module using the as clause. For example, in


import qualified Complex as C
entities must be referenced using `C.' as a qualifier instead of `Complex.'. This also allows a different module to be substituted for Complex without changing the qualifiers used for the imported module. It is an error for more than one module in scope to use the same qualifier. Qualifiers can only be used for imported entities: locally defined names within a module may not include a qualifier.

Since qualifier names are part of the lexical syntax, no spaces are allowed between the qualifier and the name. Sample parses are shown below.

This Lexes as this
f.g f . g (three tokens)
F.g F.g (qualified `g')
f.. f .. (two tokens)
F.. F.. (qualified `.')
F. F . (two tokens)

It may be that a particular entity is imported into a module by more than one route --- for example, because it is exported by two modules, both of which are imported by a third module. Benign name clashes of this form are allowed, but it is a static error for two different entities to have the same name. When two entities have the same name, they are considered to be the same object if and only if they are defined by the same module. Two different qualified names may refer to the same entity; the name of the importing module does not affect the identity of an entity.

It is an error for two different entities to have the same name. This is valid:


module A
import B(f)
import qualified C(f)
as long as only one imported f is unqualified and f is not defined at the top level of A. Qualifiers are the only way to resolve name clashes between imported entities.

5.1.3 Importing and Exporting Instance Declarations

Instance declarations cannot be explicitly named on import or export lists. All instances in scope within a module are always exported and any import brings all instances in from the imported module. Thus, an instance declaration is in scope if and only if a chain of import declarations leads to the module containing the instance declaration. For example, import M() would not bring any new names in scope from module M, but would bring in any instance visible in M.

5.2 Closure

Every module in a Haskell program must be closed. That is, every name explicitly mentioned by the source code must be either defined locally or imported from another module. Entities which the compiler requires for type checking or other compile time analysis need not be imported if they are not mentioned by name. The Haskell compilation system is responsible for finding any information needed for compilation without the help of the programmer. That is, the import of a variable x does not require that the datatypes and classes in the signature of x be brought into the module along with x unless these entities are referenced by name in the user program. The Haskell system silently imports any information which must accompany an entity for type checking or any other purposes. Such entities need not even be explicitly exported: the following program is valid even though T does not escape M1:

module M1(x) where
data T = T
x = T

module M2 where
import M1(x)
y = x
In this example, there is no way to supply an explicit type signature for y since T is not in scope. Whether or not T is explicitly exported, module M2 knows enough about T to correctly type check the program.

The type of an exported entity is unaffected by non-exported type synonyms. For example, in


module M(x) where
type T = Int
x :: T
x = 1
the type of x is both T and Int; these are interchangeable even when T is not in scope. That is, the definition of T is available to any module which encounters it whether or not the name T is in scope. The only reason to export T is to allow other modules to refer it by name; the type checker find the definition of T if needed whether or not it is exported.

5.3 Standard Prelude

Many of the features of Haskell are defined in Haskell itself as a library of standard datatypes, classes, and functions, called the "Standard Prelude." In Haskell, the Prelude is contained in the the module Prelude. There are also many predefined library modules which provide less frequently used functions and types. For example, arrays, tables, and most of the input/output are all part of the standard libraries. These are defined in the Haskell Library Report, a separate document. Separating libraries from the Prelude has the advantage of reducing the size and complexity of the Prelude, allowing it to be more easily assimilated, and increasing the space of useful names available to the programmer.

Prelude and library modules differ from other modules in that their semantics (but not their implementation) are a fixed part of the Haskell language definition. This means, for example, that a compiler may optimize calls to functions in the Prelude without being concerned that a future change to the program will alter the semantics of the Prelude function.

5.3.1 The Prelude Module

The Prelude module is imported automatically into all modules as if by the statement `import Prelude', if and only if it is not imported with an explicit import declaration. This provision for explicit import allows values defined in the Prelude to be hidden from the unqualified name space. The Prelude module is always available as a qualified import: an implicit `import qualified Prelude' is part of every module and names prefixed by `Prelude.' can always be used to refer to entities in the Prelude.

The semantics of the entities in Prelude is specified by an implementation of Prelude written in Haskell, given in Appendix A. Some datatypes (such as Int) and functions (such as Int addition) cannot be specified directly in Haskell. Since the treatment of such entities depends on the implementation, they are not formally defined in the appendix. The implementation of Prelude is also incomplete in its treatment of tuples: there should be an infinite family of tuples and their instance declarations, but the implementation only gives a scheme.

5.3.2 Shadowing Prelude Names

The rules about the Prelude have been cast so that it is possible to use Prelude names for nonstandard purposes; however, every module that does so must have an import declaration that makes this nonstandard usage explicit. For example:


     module A where
     import Prelude hiding (null)
     null x = []
Module A redefines null, but it must indicate this by importing Prelude without null. Furthermore, A exports null, but every module that imports null unqualified from A must also hide null from Prelude just as A does. Thus there is little danger of accidentally shadowing Prelude names.

It is possible to construct and use a different module to serve in place of the Prelude. Other than the fact that it is implicitly imported, the Prelude is an ordinary Haskell module; it is special only in that some objects in the Prelude are referenced by special syntactic constructs. Redefining names used by the Prelude does not affect the meaning of these special constructs. For example, in


module B where
import qualified Prelude
import MyPrelude
      ...
B imports nothing from Prelude, but the explicit import qualified Prelude declaration prevents the automatic import of Prelude. import MyPrelude brings the non-standard prelude into scope. As before, the standard prelude names are hidden explicitly. Special syntax, such as lists or tuples, always refers to prelude entities: there is no way to redefine the meaning of [x] in terms of a different implementation of lists.

5.4 Separate Compilation

Depending on the Haskell implementation used, separate compilation of mutually recursive modules may require that imported modules contain additional information so that they may be referenced before they are compiled. Explicit type signatures for all exported values may be necessary to deal with mutual recursion. The precise details of separate compilation are not defined by this report.

5.5 Abstract Datatypes

The ability to export a datatype without its constructors allows the construction of abstract datatypes (ADTs). For example, an ADT for stacks could be defined as:


module Stack( StkType, push, pop, empty ) where
	data StkType a = EmptyStk | Stk a (StkType a)
	push x s = Stk x s
	pop (Stk _ s) = s
	empty = EmptyStk
Modules importing Stack cannot construct values of type StkType because they do not have access to the constructors of the type.

It is also possible to build an ADT on top of an existing type by using a newtype declaration. For example, stacks can be defined with lists:


module Stack( StkType, push, pop, empty ) where
	newtype StkType a = Stk [a]
	push x (Stk s) = Stk (x:s)
	pop (Stk (x:s)) = Stk s
	empty = Stk []

5.6 Fixity Declarations

fixdecls      -> fix1 ; ... ; fixn                        
fix           -> infixl [digit] ops 
              |  infixr [digit] ops
              |  infix  [digit] ops 
ops           -> op1 , ... , opn                          
op            -> varop | conop 
A fixity declaration gives the fixity and binding precedence of a set of operators. Fixity declarations must appear only at the start of a module and may only be given for identifiers defined in that module. Fixity declarations cannot subsequently be overridden, and an identifier can only have one fixity definition.

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 digit is omitted, level 9 is assumed. Any operator lacking a fixity declaration is assumed to be infixl 9 (See Section 3 for more on the use of fixities). Table 2 lists the fixities and precedences of the operators defined in the Prelude.

Prec- Left associative Non-associative Right associative
edence operators operators operators
9 !! .
8 ^, ^^, **
7 *, /, `div`,
`mod`, `rem`, `quot`
6 +, -
5 \\ :, ++
4 ==, /=, <, <=, >, >=,
`elem`, `notElem`
3 &&
2 ||
1 >>, >>=
0 $, `seq`

Table 2

Precedences and fixities of prelude operators

Fixity is a property of the name of an identifier or operator: the same fixity attaches to every occurrence of an operator name in a module, whether at the top level or rebound at an inner level. For example:


module Foo
import Bar
infix 3 `op`

f x = ... where p `op` q = ...
Here `op` has fixity 3 wherever it is in scope, provided Bar does not export the identifier op. If Bar does export op, then the example becomes invalid, because the fixity (or lack thereof) of op is defined in Bar (or wherever Bar imported op from). If op is imported as a qualified name from Bar, no conflict may occur: the fixity of a qualified name does not affect unqualified uses of the same name.

Next section: Basic Types
The Haskell 1.3 Report