KatInterview

Principal Types for a Tiny Lambda Calculus

Trees & GraphsModel answer
HardModel answerTrees & Graphstype-inferenceunificationhindley-milner

Last updated

Build an AST for variables, lambdas and applications, then infer each expression's most general function type using unification, with an occurs check to reject infinite types.

Task

You are building the type checker for a very small functional language. Programs are trees made of three node kinds:

  • Var(name) is a reference to a variable.
  • Abs(param, body) is a one-argument function (a lambda) that binds param inside body.
  • App(fn, arg) calls fn with arg.

There are no literals, no let, and no built-in types. The only types are unknown type variables and function types.

Write a class TypeInferencer with a method infer(expr) -> str. It must return the most general (principal) type of expr as a string, or raise UnificationError if the expression cannot be typed.

Output format

  • Type variables are written T0, T1, T2, and so on. They are numbered in the order they first appear when reading the final string from left to right, regardless of how many temporary variables you created internally.
  • A function type from A to B is written (A -> B). Every arrow gets its own pair of parentheses, so nesting looks like (T0 -> (T1 -> T0)).

Examples

ExpressionResult
Abs("x", Var("x"))"(T0 -> T0)"
Abs("x", App(Var("x"), Var("x")))raises UnificationError (it would need an infinite type)
Abs("f", Abs("x", App(Var("f"), Var("x"))))"((T0 -> T1) -> (T0 -> T1))"
Abs("x", Abs("x", Var("x")))"(T0 -> (T1 -> T1))"

Rules and constraints

  • Input expressions are finite trees.
  • Scoping is lexical. An inner binder with the same name shadows the outer one only inside its own body.
  • A variable that is not bound by any enclosing Abs must raise a separate UnboundVariableError, so that callers can tell it apart from a type conflict.
  • Calling infer several times on the same object must give deterministic results, so each call has to start with fresh numbering.

What to deliver

Explain your approach, give the data structures for the AST and for types, implement infer, and state the time and space complexity. Be ready to explain why self-application fails and how you would extend the system with polymorphic let.

Hints

Hint 1

Treat inference as constraint solving. Give every lambda parameter a brand-new unknown type, and let the rules for each node tell you which unknowns must be equal.

Hint 2

For an application, infer the types of the function and the argument, invent a fresh unknown for the result, and demand that the function's type equals 'argument type -> result'. Making two types equal is exactly what unification does.

Hint 3

Before binding a type variable to a type, check that the variable does not occur inside that type. Skipping this check lets x x slip through with a cyclic type. Also rename variables only when printing, in order of first appearance.