Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 57 ยท Modules, packages and tooling

Modules and Imports

Organize Haskell code with modules: the module header, export lists, qualified imports, hiding Prelude names and fixing ambiguous name clashes.

Once a program outgrows one file, you split it into modules. A module is a file that groups related definitions and decides which of them other files may see. Haskell's module system is deliberately simple: there are no classes of modules, no namespaces beyond the module name, and almost everything is about what to export and what to import.

This lesson covers the module header, export lists, the different forms of import, and how to resolve name clashes. Real Haskell is read-only on this site; the runnable blocks are JavaScript stand-ins that mimic export lists and qualified names with objects and closures.

One file, one module

A module starts with a header. The file name must match the module name, with dots turned into folders:

HASKELL
-- file: src/Geometry/Shapes.hs
module Geometry.Shapes
  ( Shape (..)
  , area
  , perimeter
  , unitSquare
  ) where

data Shape = Circle Double | Rect Double Double
  deriving Show

area :: Shape -> Double
area (Circle r)   = pi * r * r
area (Rect w h)   = w * h

perimeter :: Shape -> Double
perimeter (Circle r) = 2 * pi * r
perimeter (Rect w h) = 2 * (w + h)

unitSquare :: Shape
unitSquare = Rect 1 1

-- not exported: a private helper
square :: Double -> Double
square x = x * x

The names in parentheses form the export list. Everything not listed (here square) stays private to the module. If you omit the list entirely, every top-level name is exported, which is handy in small programs but leaves nothing private.

A program's entry module is Main, and it must export main. If a file has no header, GHC assumes module Main (main) where. A typical project layout:

TEXT
myapp/
  app/Main.hs              -- module Main
  src/Geometry/Shapes.hs   -- module Geometry.Shapes
  src/Geometry/Utils.hs    -- module Geometry.Utils

The module name Geometry.Shapes is only a naming convention for a hierarchy: there is no real parent-child relationship between Geometry and Geometry.Shapes.

Controlling exports

Exporting a data type has three forms:

Export What is visible
Shape The type only, no constructors
Shape (Circle, Rect) The listed constructors
Shape (..) All constructors (and record fields)

Exporting a type without its constructors makes it abstract: users can hold values of the type but can only create and inspect them through your functions. That is how you protect an invariant:

HASKELL
module Email (Email, mkEmail, emailText) where

newtype Email = Email String

mkEmail :: String -> Maybe Email
mkEmail s
  | '@' `elem` s = Just (Email s)
  | otherwise    = Nothing

emailText :: Email -> String
emailText (Email s) = s

Outside Email, no code can build an Email without the @ check. You can also re-export a whole imported module with module Data.List in the export list, which is useful for "facade" modules. Type class instances are always exported with the module that defines them; there is no way to hide one.

Anatomy of a module

Header The name, matching the file path.
Export list Which names others can use.
Imports Names taken from other modules.
Definitions Types, classes and functions.
1 / 2
JS Export lists and abstract types (a stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Importing

An import goes at the top of the file, after the header, before any definitions:

HASKELL
import Data.Char                          -- everything Data.Char exports
import Data.List (sortBy, nub)            -- only these two names
import Data.Ord (comparing)
import Data.Maybe hiding (fromJust)       -- all but fromJust
import Data.Map (Map)                     -- just the type name
import qualified Data.Map as Map          -- names need the prefix Map.

import Data.List (sortBy) is explicit and easy to read: a reader sees where every name comes from. Importing a whole module (import Data.Char) brings in many names, which makes it harder to trace a function back to its source and raises the chance of clashes.

You can import types with their constructors: import Data.Maybe (Maybe (..)), import Data.Map (Map). A class can be imported with its methods: import Data.Foldable (Foldable (..)).

The Prelude

The Prelude is a module imported implicitly into every module. It contains map, filter, show, putStrLn, Maybe and the rest of the everyday vocabulary. It behaves as if the first line of your file were import Prelude. To change that, import it yourself with a hiding list; GHC then does not add the implicit import:

HASKELL
import Prelude hiding (lookup, filter)

The extension NoImplicitPrelude turns the implicit import off entirely, which alternative preludes (such as relude) use.

Qualified imports and name clashes

Many modules reuse the names of Prelude functions, because they offer the same operation on another structure: Data.Map.filter, Data.Map.map, Data.Map.lookup, Data.Text.length. If you import them unqualified, using the name is ambiguous, and GHC reports an error like this:

TEXT
Ambiguous occurrence 'filter'
It could refer to
   either 'Prelude.filter', imported from 'Prelude'
       or 'Data.Map.filter', imported from 'Data.Map'

The standard remedy is the qualified import, which requires a prefix for every name:

HASKELL
import qualified Data.Map as Map
import qualified Data.Text as T
import Data.Map (Map)     -- the type itself is used unqualified

wordCounts :: [String] -> Map String Int
wordCounts ws = Map.fromListWith (+) [(w, 1) | w <- ws]

main :: IO ()
main = do
  let m = wordCounts (words "a b a c b a")
  print (Map.toList m)
  print (Map.lookup "a" m)
  print (filter even [1 .. 10])         -- Prelude's filter
  print (Map.filter (> 1) m)            -- Map's filter

Common conventions: Map for Data.Map, Set for Data.Set, T for Data.Text, BS for Data.ByteString, V for Data.Vector. Modern GHC also accepts the prefix form of the keyword at the end, import Data.Map qualified as Map, enabled by ImportQualifiedPost (included in GHC2021, the default language edition for new projects).

Other ways to settle clashes:

  • hiding: import Data.List hiding (insert) when you define your own insert.
  • Qualified reference to a local name: if you define lookup yourself and also keep the Prelude's, write Prelude.lookup or Main.lookup to choose.
  • An alias shared by several imports: import qualified Data.Map as M and import qualified Data.Map.Strict as M is allowed, but keep it clear which one you want. In real code, prefer Data.Map.Strict to avoid thunk build-up in values.
JS Qualified names, the Map. prefix (a stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Good habits

  • Write an explicit export list for library modules, and keep constructors hidden when they carry invariants.
  • Import names explicitly (import Data.List (sortBy)) or qualify large modules (Map, Set, Text).
  • To import a module only for its type class instances, write import Mod (), which brings in no names.
  • Modules cannot import each other in a cycle. If A and B need each other's types, move the shared types to a third module C that both import.
  • Group imports: standard library first, then packages, then your own modules.

Packages that bundle many modules, and how Cabal finds them, come next in Cabal, Stack and Packages.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does exporting Shape (without (..)) do?

    The type becomes abstract: users can name it and pass values around, but can only create or inspect them through exported functions.
  2. 2. Which line imports Data.Map so that you write Map.lookup?

    qualified ... as requires the alias prefix for every name from the module.
  3. 3. You define your own lookup in a module that uses the implicit Prelude. What happens when you call lookup?

    A top-level definition and an imported name clash when used unqualified. Use import Prelude hiding (lookup) or Main.lookup.
  4. 4. Can module A import module B while B imports A?

    Cycles are rejected; move the shared definitions into a third module.

Summary

  • A module is a file whose header names it and whose export list controls what others see.
  • Exporting a type without its constructors makes it abstract and protects invariants.
  • Import explicitly, hide what you do not want, or use qualified ... as for names that clash with the Prelude.
  • The Prelude is imported implicitly unless you import it yourself or disable it.
  • Cyclic imports are not allowed; share types through a third module.

Next, we manage whole projects and dependencies: Cabal, Stack and Packages.