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.PersonExplanation
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
Types and Type Classes
Define algebraic data types and type classes.
Maybe and IO Monads
Use Maybe for safety and IO for side effects.
List Comprehensions and Laziness
Generate lists with comprehensions and leverage laziness.
Functors, Applicatives, Monad Type Classes
The three core abstraction type classes.
IO and do Notation
Side-effectful programming in Haskell.
Laziness and Strictness
Understand lazy evaluation and when to be strict.