Skip to content
Haskell

Types and Type Classes

Define algebraic data types and type classes.

#type#type-class#adt

Code

haskell
-- Algebraic data type
data Shape
  = Circle { radius :: Double }
  | Rectangle { width :: Double, height :: Double }
  | Triangle { a :: Double, b :: Double, c :: Double }
  deriving (Show, Eq)

-- Type class
class Area a where
  area :: a -> Double

instance Area Shape where
  area (Circle r) = pi * r * r
  area (Rectangle w h) = w * h
  area (Triangle x y z) =
    let s = (x + y + z) / 2
    in sqrt (s * (s - x) * (s - y) * (s - z))

-- Newtype (zero-cost wrapper)
newtype UserId = UserId Int deriving (Show, Eq)

-- Type alias
type Point = (Double, Double)

-- Usage
main :: IO ()
main = do
  let c = Circle 5
  let r = Rectangle 3 4
  print c            -- Circle {radius = 5.0}
  print (area c)     -- 78.53981633974483
  print (area r)     -- 12.0