3-2-Module
3-2-Module
Yuepeng Wang
Spring 2025
1
Overview
• Importing modules
• Defining modules
2
Modules
• We have been mostly writing functions so far
3
Advantages of Modules
• Code reuse
• Code management
• The code is more manageable when you split it into several parts
4
Importing Modules
• Syntax: import ModuleName
• nub is a function in Data.List that takes a list and returns another list with
all duplicates removed
5
Importing Modules
• How to selectively import a few functions?
https://hoogle.haskell.org
6
Example: Data.Char
• Given an Int, compute the sum of all its digits
7
Qualified Imports
• What if you need to import two functions with the same name?
• How does Haskell know the dot is not the function composition?
• The dot is between a qualified name and a function, without whitespaces
• You can rename the qualified import to make the name shorter
import qualified Data.List as L
8
Example: Data.Map
• The Map (sometimes referred to as Dictionary) data structure can store
associations between unique keys and values
9
Defining Modules
• When defining a module, we only export those functions that act as the
“interface” and hide other functions for internal implementation
Geometry.hs
module Geometry
( sphereArea, cubeArea ) where
10
Hierarchical Modules
• Modules can have a hierarchical structure
• Each module can have several submodules, which can also have their
own submodules
Geometry/Sphere.hs Geometry/Cube.hs
module Geometry.Sphere module Geometry.Cube
( area ) where ( area ) where
11