Type Signatures, Polymorphism and Type Inference

Type inference: GHC infers the most general type. Still, write top-level type signatures as documentation and to get better error messages.

Parametricity ("theorems for free"): a function f :: a -> a can only be id (or loop forever / crash). [a] -> [a] can only rearrange, drop, or duplicate elements, never invent new ones.

Typed holes: write _ in an expression and GHC tells you the expected type and suggests fits:

Type applications (TypeApplications, in GHC2021): read @Int "42", show @Double 3.

-- Monomorphic
not' :: Bool -> Bool

-- Parametric polymorphism: works for ANY type a
identity :: a -> a
identity x = x

first :: (a, b) -> a
first (x, _) = x

-- Constrained (ad-hoc) polymorphism: type class constraints
largest :: Ord a => [a] -> a
largest = maximum

showAll :: Show a => [a] -> String
showAll = unwords . map show

sumAndShow :: (Num a, Show a) => [a] -> String
sumAndShow xs = show (sum xs)
mystery :: [Int] -> Int
mystery xs = foldr _ 0 xs
-- error: Found hole: _ :: Int -> Int -> Int ... Valid hole fits include (+), (-), max, min ...

9.1 Type Synonyms and Common Numeric Classes

+ - * negate abs signum fromInteger Int, Integer, Double,...

div mod quot rem toInteger / recip fromRational Double, Float, Rational sqrt exp log sin pi ** Real, RealFrac, RealFloat Conversions, rounding

type Name = String
type Point = (Double, Double)
type Assoc k v = [(k, v)]

distance :: Point -> Point -> Double
distance (x1, y1) (x2, y2) = sqrt ((x2 - x1) ^ 2 + (y2 - y1) ^ 2)