Lesson 6: Modules

A Haskell module, at its core, is just a collection of related functions, types and typeclasses. That means that a Haskell program is a collection of modules where the main module loads up the other modules and then uses the functions defined in them to execute the program.

In JS terms, think about this in the light of modular vs monolithic applications

The syntax for importing modules is import <module name> (similar to an ES6 import, just without the from declaration). If you only want to expose certain functions within a module, we can use import <module name> (fx, gx). You can also choose to import all of the functions from a module while except a select few by import <module name> hiding (fx).

When using functions that have a shared name with a funciton in the standard libray, like filter in Data.Map, we have to include the Data.Map declaration in front of the function so that Haskell does not get confused. Although, typing out Data.Map.filter every time we want to use that function sucks. We alias Data.Map by importing it like thus: import qualified Data.Map as M. Then we just have to call M.filter. Much better.

ghci> import Data.List
ghci> "needle" `isInfixOf` `hayneedlestack`
True

Defining modules

The name of our module is defined by the name of the module file. If we have a file named Geometry.hs, then our module should be named Geometry. We then can specify the functions it exports and then write those functions.

module Geometry
( sphereVolume
, sphereArea
, cubeVolume
, cubeArea
, cuboidArea
, cuboidVolume
) where

sphereVolume :: Float -> Float
sphereVolume radius = (4.0 / 3.0) * pi * (radius ^ 3)

...

If we wanted to import a collection of modules similar to Data.Map. We can create a Geometry folder and then create the related module files. In the Geometry folder, we can place Sphere.hs, Cuboid.hs, and Cube.hs. This is what a module file would then look like:

module Geometry.Sphere
( volume
, area
) where

volume :: Float -> Float
volume radius = (4.0 / 3.0) * pi * (radius ^ 3)

...

We can then use qualified imports, as outlined earlier, to import our functions.

import qualified Geometry.Sphere as Sphere
import qualified Geometry.Cuboid as Cuboid
import qualified Geometry.Cube as Cube

results matching ""

    No results matching ""