Skip to content

Add Hindley-Milner type inference for recursive functions#15

Open
jacobaustin123 wants to merge 2 commits intomasterfrom
hindley-milner-inference
Open

Add Hindley-Milner type inference for recursive functions#15
jacobaustin123 wants to merge 2 commits intomasterfrom
hindley-milner-inference

Conversation

@jacobaustin123
Copy link
Owner

Summary

This PR implements Hindley-Milner type inference for Coral, enabling the compiler to correctly infer types for recursive functions.

Before this change:

  • Recursive function calls would short-circuit and return dyn type
  • Functions like factorial(n) and fibonacci(n) would be typed as dyn even though they clearly return integers

After this change:

  • Recursive functions correctly infer their return types through unification
  • factorial(5) is now typed as int instead of dyn
  • All existing tests continue to pass

Changes

  • src/infer.ml (new): Core HM inference module with type variables, substitution, and unification
  • src/ast.ml: Added TVar of int to the type system for type variables
  • src/semant.ml: Updated recursive call handling to use type variables and unification for branch reconciliation
  • src/utilities.ml: Added TVar support and substitution field to inference state
  • tests/hm-test-*.cl: New test cases for recursive type inference

Type Inference Results

Function Before After
factorial(n) dyn int
fibonacci(n) dyn int
sum_to_n(n) dyn int
power(x, n) dyn int
gcd(a, b) dyn int

Test plan

  • All 125 existing tests pass
  • New HM-specific tests verify correct type inference for recursive functions
  • Gradual typing preserved: Dyn still works as the dynamic type escape hatch

🤖 Generated with Claude Code

@jacobaustin123 jacobaustin123 force-pushed the hindley-milner-inference branch from fa85e45 to 0b8091e Compare January 3, 2026 03:37
@jacobaustin123 jacobaustin123 force-pushed the hindley-milner-inference branch from 0b8091e to 782be33 Compare January 4, 2026 01:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant