Reputation: 3237
Is there any type inference algorithm that can always (or almost always) infer the correct type? I know that the Hindley Milner algorithm can do it in quite a bit of cases but not all of them (i.e., higher-rank polymorphic types).
Upvotes: 0
Views: 163
Reputation: 183564
Your question isn't entirely well-posed, because the set of "all cases" isn't entirely well-defined.
For example, you mention higher-rank polymorphic types as a case where Hindley–Milner type inference can't always infer the right type, which is true, except that there are languages such as Standard ML and Haskell that use Hindley–Milner type inference and don't have higher-rank polymorphic types. In fact, Hindley–Milner algorithms do work in all cases covered by the Hindley–Milner type system; that is, the Hindley–Milner system allows exactly the types that can be inferred by Hindley–Milner type inference algorithms, and explicit type annotations are therefore never needed in that system.
Of course, real-world languages using Hindley–Milner typically extend the system in various ways for pragmatic reasons, and some of those extensions result in cases that the algorithm doesn't cover. (For example, Standard ML has some built-in overloaded identifiers, such as + : real * real -> real
and + : int * int -> int
, which means that programmers sometimes need to use explicit type annotations in order to choose the right overload.) But that is a design decision, not a necessity; and I notice that you don't mention any real-world languages in your question, anyway.
But it seems from your question that you want at least all of Hindley–Milner plus higher-rank polymorphic types. That means that you want at least all of System F, the polymorphic lambda calculus. And type inference in System F is known to be undecidable. This means that the answer to your question is "no": no type inference algorithm can infer the correct types for all the cases you seem to want.
Upvotes: 1