🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Modules

A module is a library file that groups related Haskell helpers. An import line brings chosen helpers from a module into a program.

Data.Char helpers for text

The import brings in toUpper and isDigit from Data.Char. The program uses both of them.

import Data.Char (toUpper, isDigit)
main :: IO ()
main = do
  putStrLn (map toUpper "haskell")
  print (isDigit '7')

Data.List brings in sort

sort does not come with the basic helpers. The import brings it in from Data.List.

import Data.List (sort)
main :: IO ()
main = print (sort [5, 2, 8, 1])

A qualified import keeps the module name

This import gives Data.List the short name List. Each use then starts with List and a dot.

import qualified Data.List as List
main :: IO ()
main = print (List.sort [9, 4, 6])

Example

import Data.Char (toUpper)
import Data.List (sort)
main :: IO ()
main = do
  putStrLn (map toUpper "cat")
  print (sort [3, 1, 2])

Key points

  • import: a line at the top of a program that brings helpers in from a module.
  • Named helpers: names in round brackets after the module name list exactly what is brought in.
  • Data.Char: a module that holds helpers for single characters and text.
  • Data.List: a module that holds extra helpers for lists.
  • Qualified import: an import that keeps the module name in front of each helper, such as List.sort.
  • Top of the file: import lines sit above every definition in the program.

In this example, the first import brings toUpper in from Data.Char and the second brings sort in from Data.List. The first action prints CAT, using toUpper on each letter. The second action prints the sorted list.

Note

helpers that are not imported stay out of reach, even if the module holds them.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Which line brings the sort helper in from Data.List?