Skip to content
Haskell

Modules and Imports

Organize code with modules and control exports.

By EZ4Code Team
moduleimportexport

Code

-- File: MyModule.hs
module MyModule
  ( -- Export only these
    greet
  , Person(..)        -- exports type and all constructors
  , mkPerson
  ) where

import Data.List (sort, nub)        -- specific functions
import qualified Data.Map as M      -- qualified (M.lookup)
import Data.Maybe (fromJust, isJust)

-- Define and export
data Person = Person { pName :: String, pAge :: Int }
  deriving (Show, Eq)

greet :: Person -> String
greet (Person name _) = "Hello, " ++ name

mkPerson :: String -> Int -> Maybe Person
mkPerson name age
  | age < 0    = Nothing
  | otherwise  = Just (Person name age)

-- Usage in another module:
-- import MyModule (greet, Person(..), mkPerson)
-- import qualified MyModule as M  -- M.greet, M.Person

Explanation

Modules control visibility — only exported names are accessible. (..) exports all constructors; (Type) exports only the type (opaque). import Foo brings all exports into scope; import Foo (bar) imports only bar; import qualified Foo as F forces F.bar prefix. Use qualified imports for libraries with common names (Data.Map) to avoid clashes.

More Haskell Snippets