Haskell
02 / 02

Haskell Fundamentals: Purity, Laziness & the Type System

Haskell: Purity, Laziness & the Type System

Haskell is a purely functional programming language with a strong, static type system -- distinguished by default immutability, lazy evaluation, and functions with no side effects unless explicitly tracked in the type system. Widely used in academia/research, with growing industry adoption for high-correctness domains.

Purity: Side Effects Tracked in Types

-- No IO in the type -- guaranteed to have no side effects,
-- always returns the same output for the same input
double :: Int -> Int
double x = x * 2

-- IO in the type -- the type signature itself makes the
-- side-effecting capability visible
main :: IO ()
main = do
  line <- getLine
  putStrLn ("You said: " ++ line)

Lazy Evaluation

-- An INFINITE list -- only computes elements as they're demanded
naturals :: [Integer]
naturals = [1..]

take 5 naturals  -- => [1,2,3,4,5]
-- Would never terminate under eager evaluation, which would try
-- to fully compute the infinite list upfront

Maybe: No More Null

safeDivide :: Int -> Int -> Maybe Int
safeDivide _ 0 = Nothing
safeDivide x y = Just (x `div` y)

-- Caller MUST handle both cases -- compiler enforces it
case safeDivide 10 0 of
  Just result -> print result
  Nothing     -> putStrLn "Cannot divide by zero"

-- Directly predates/influenced F#'s Option, Rust's Option,
-- Swift's optionals -- same underlying goal, avoiding null-reference errors

Algebraic Data Types

-- Precisely models valid possibilities -- an invalid combination
-- (Completed with a failure message) is structurally unrepresentable
data PaymentStatus
  = Pending
  | Completed TransactionId
  | Failed String

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free