Haskell Modules & Imports
A module is a file of related definitions with a name such as Data.List or Geometry.Shapes. Modules organise large programs and libraries, control what is visible from outside, and avoid name clashes. Every Haskell file is a module; when you don't write a header, it is module Main.
The Prelude module is imported automatically. It contains the basics you have used so far: map, filter, foldr, show, putStrLn and many more. Everything else must be imported.
Import styles
import Data.List (sort, group) -- only these names
import Data.Char hiding (isSpace) -- everything except isSpace
import qualified Data.Map as Map -- names only as Map.something
import Data.Maybe -- everything the module exports
main :: IO ()
main = do
print (map (\g -> (head g, length g)) (group (sort "mississippi")))
print (map toUpper "imported")
print (Map.toList (Map.fromList [(2, "two"), (1, "one")]))
print (catMaybes [Just 1, Nothing, Just 3])[('i',4),('m',1),('p',2),('s',4)]
"IMPORTED"
[(1,"one"),(2,"two")]
[1,3]
| Form | Brings into scope |
|---|---|
import M |
every exported name, unqualified |
import M (a, b) |
only a and b (recommended for small imports) |
import M hiding (c) |
everything except c |
import qualified M |
every name, but only as M.name |
import qualified M as X |
every name as X.name |
import M (T (..)) |
type T with all its constructors |
Tip: Modules such as
Data.Map,Data.SetandData.Textdefine functions namedfilter,map,lookupandnull, which clash with the Prelude. Always import them qualified:import qualified Data.Map as Map. The name afterasis up to you;Map,M,Set,SandTare conventional.
Name clashes
If two imported modules export the same name and you use it unqualified, GHC refuses to guess:
import Data.Map (filter)
main :: IO ()
main = print (filter even [1, 2, 3, 4])<source>:4:15: error: [GHC-87543]
Ambiguous occurrence `filter'.
It could refer to
either `Prelude.filter',
imported from `Prelude' at <source>:1:1
(and originally defined in `GHC.Internal.List'),
or `Data.Map.filter',
imported from `Data.Map' at <source>:1:18-23
(and originally defined in `Data.Map.Internal').
|
4 | main = print (filter even [1, 2, 3, 4])
| ^^^^^^
Qualified imports avoid the problem entirely.
Modules worth knowing
| Module | Highlights |
|---|---|
Data.List |
sort, sortOn, nub, group, partition, intercalate, isPrefixOf, foldl', transpose |
Data.Char |
toUpper, isDigit, isAlpha, ord, chr |
Data.Maybe |
fromMaybe, mapMaybe, catMaybes, isJust |
Data.Either |
lefts, rights, partitionEithers, either |
Data.Map.Strict |
key-value dictionaries (next lesson) |
Data.Set |
sets of unique, ordered values (next lesson) |
Data.Ord |
comparing, Down |
Data.Function |
on, & |
Text.Printf |
C-style formatted output |
Text.Read |
readMaybe |
Control.Monad |
forM_, when, unless, replicateM, foldM |
A few of them in action:
import Data.List (partition, transpose, groupBy, sortOn)
import Data.Function (on)
import Text.Printf (printf)
import Control.Monad (forM_, when)
main :: IO ()
main = do
let (passed, failed) = partition (>= 50) [72, 35, 90, 48, 61]
print (passed, failed)
print (transpose [[1, 2, 3], [4, 5, 6]])
let people = [("Ana", "dev"), ("Bo", "ops"), ("Cy", "dev")]
print (groupBy ((==) `on` snd) (sortOn snd people))
forM_ [("tea", 3.5), ("cake", 4.25)] $ \(item, price) ->
printf "%-6s %6.2f\n" (item :: String) (price :: Double)
when (length failed > 1) $ putStrLn "Several students need a retake."([72,90,61],[35,48])
[[1,4],[2,5],[3,6]]
[[("Ana","dev"),("Cy","dev")],[("Bo","ops")]]
tea 3.50
cake 4.25
Several students need a retake.
printf works much like C's: %-6s is a left-aligned string in 6 columns, %6.2f a number with 2 decimals in 6 columns. It needs to know the argument types, hence the annotations.
Writing your own module
In a project, each module lives in its own file whose path matches the module name: Geometry/Shapes.hs holds module Geometry.Shapes. The export list in parentheses decides what other modules can see:
-- file: src/Geometry/Shapes.hs
module Geometry.Shapes
( Shape (..) -- the type and its constructors
, area
, perimeter -- helper functions not listed here stay private
) where
data Shape = Circle Double | Rect Double Double
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)-- file: app/Main.hs
module Main (main) where
import Geometry.Shapes (Shape (..), area)
main :: IO ()
main = print (area (Rect 3 4))The playground compiles a single file, so the examples in this course keep everything in one module. The ideas carry over directly to multi-module Cabal projects, where you list modules under exposed-modules or other-modules in the .cabal file.
Note: Exporting a type without its constructors,
module Bank (Account, openAccount) where, is the Haskell way to make an abstract data type: other modules can use the functions you export but cannot build or inspect anAccountdirectly.
Test yourself
Which import lets you use Map.lookup but not a bare lookup from Data.Map?
import Data.Mapimport Data.Map (lookup)import qualified Data.Map as Mapimport Data.Map hiding (lookup)
Which module is imported automatically?
Data.ListPreludeData.CharControl.Monad
In module Shapes (Shape, area) where, what can other modules do with Shape?
- Use its constructors freely
- Use the type name, but not its constructors
- Nothing
- Only pattern match on it