Type Signature Serialization & Inference — OpenAI
Question Description
You must design a small, readable textual format for type signatures and implement data structures and an inference routine that work with that format.
Start by defining a concise serialization that can express primitive types (char, int, float, str), named type variables (T1, T2), tuples (e.g. [int, char]), and function types (params -> return). The format must be deterministic so identical types always serialize to the same string, and tuple/parameter lists must be unambiguous (for example, bracketed lists and a parenthesized parameter list with ->).
Implement a Node abstraction that represents either an atomic type (primitive or named variable) or a tuple (a list of child Nodes). Implement a Function abstraction that holds an ordered list of parameter Nodes and a single output Node, with stable to_str serialization for both Node and Function.
Implement type-variable inference: given a Function signature that may contain named type variables and a list of concrete parameter Nodes (no generics), infer a mapping from each type variable to a concrete Node and return the output Node with variables substituted. Your inference must check for incorrect argument counts, structural mismatches (tuple arity/shape), and conflicting assignments for the same type variable and raise clear exceptions.
Flow in an interview: describe the format, implement Node/Function, write deterministic to_str, then implement structural matching and unification-style inference, and test with positive and negative examples. Skills signaled: tree traversal, unification/type inference, deterministic serialization, and careful error handling.
Common Follow-up Questions
- •How would you extend the format and inference to support higher-order functions (function types as parameters and returns)?
- •Describe and implement an occurs-check to prevent infinite types (e.g., T = [T]) during unification—how does it change the algorithm?
- •How would you modify inference to allow variance or subtyping (e.g., covariant returns) instead of exact structural equality?
- •Show how to use a union-find (disjoint set) or explicit unification data structure to make repeated type-variable merging efficient and deterministic.
Related Questions
Explore More Questions
Practice This Question with AI
Get real-time hints, detailed requirements, and insightful analysis of the question.