Skip to content

Lesson 2 of 9 · 24m

Type Inference and Local Reasoning

Read inferred types accurately, recognize unification failures, and decide where annotations are documentation rather than noise.

New OCaml programmers often treat type inference as a parlor trick: look, no annotations! Then the first real error arrives — 'This expression has type int but an expression was expected of type string' — and they start randomly annotating values until the message moves. That is backwards. Inference is a proof search over your program. Read it as a compiler explaining where two explanations of the data stopped agreeing.

Inference is not dynamic typing with better marketing

This function has no annotations:

type item = { price : float }
let total_price items =
  List.fold_left (fun acc item -> acc +. item.price) 0.0 items

OCaml infers val total_price : item list -> float. There is no runtime dictionary lookup waiting to fail. Once the record label price is in scope, the compiler proves field use, list shape, and arithmetic are consistent before the program runs.

Unification is the central operation

When inference sees x + y, it requires both sides to support integer addition in this context. When it later sees x used as a string, the two requirements cannot unify. The compiler reports the conflict, but the reported line is not always the root mistake. It is often merely where the contradictory uses met.

let normalize name =
  let trimmed = String.trim name in
  if trimmed = "" then None else Some trimmed

let broken input =
  match normalize input with
  | None -> 0
  | Some name -> name

This fails because the branches disagree: one is int, the other is string. The bug may be the missing conversion, but it may also be a wrong design — perhaps failure should return an error variant rather than a sentinel number. Inference failures often expose design ambiguity before runtime does.

Polymorphism is a contract about non-interference

Write a function over unknown values and the compiler uses type variables:

let pair x y = (x, y)

Its type is val pair : 'a -> 'b -> 'a * 'b; 'a means the function does not inspect or constrain the first value. That is stronger than 'any type goes.' It means behavior cannot secretly depend on that type. Parametricity is one reason ML code can be reviewed locally: a sufficiently polymorphic function has fewer ways to surprise you.

Annotate boundaries, not every expression

Good annotation style is deliberate:

type money = Money of int64
let add_cents : money -> money -> money =
  fun (Money a) (Money b) -> Money (Int64.add a b)

Annotate public module values, recursive functions that confuse inference, tricky polymorphic code, and places where the inferred type is broader than the intended contract. Do not annotate every temporary. Excess annotations become stale documentation and make refactors unnecessarily painful.

Field notes

  • Read compiler errors from the first error, not the last; cascades often follow one bad assumption.
  • _ in a type error means 'some type the compiler could not pin down here,' not permission to ignore the mismatch.
  • Type annotations at public interfaces are documentation checked by the compiler, not a failure of inference.
  • + is integer addition and +. is float addition. OCaml deliberately avoids implicit numeric coercion and ad-hoc operator overloading.

Was this lesson helpful?

Sign in to rate