Skip to content
Haskell

Types and Type Classes

Define algebraic data types and type classes.

By EZ4Code Team
typetype-classadt

Code

-- 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

Explanation

data defines sum types (| alternatives) and product types (fields). deriving auto-implements common classes (Show, Eq, Ord). class defines an interface; instance implements it for a type. newtype is a zero-cost wrapper (same representation at runtime, different at compile time). Use type for synonyms (no new type created).

More Haskell Snippets