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.0Explanation
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
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.
Modules and Imports
Organize code with modules and control exports.
Laziness and Strictness
Understand lazy evaluation and when to be strict.