by heavenlyhash · 7y ago · 0 comments
This is a very outstandingly interesting line out the whole writeup.
I like the writeup in its entirety for being very balanced and thoughtful, but this line in particular really stands out to me as worth more thought for anyone interested in language and type system design.
Inference is great.
Except... when it's not. When it's "too much". When it starts making breaking changes appear "too distantly".
It's an interesting topic to reflect upon, because the inference isn't making a breakage; just shifting around where the breakage appears. (And this makes it hard to ever direct criticism at an inference mechanism!) But this kind of shifting-around of the breakage appearance can be a drastic impact on the ergonomics of handling it: how early it's detected, how close to the important change site tooling will be able to point the coder, etc. That's important. And almost everything about it involves the word "too" -- which means the area is incredibly subjective, and requires some kind of norm-building... while not necessarily providing any clear place for that norm-building to center around.
I don't have a point here other than to say this is interesting to reflect on. I suspect the last chapter on type inference systems has not yet been written. Can an inference system be designed such that it naturally restrains "too" much use of it?
Here's a related property I've also discovered of 'advanced' type systems.
In my understanding of how unification happens in systems like H-M, you first give every expression its own type variable, then perform a search to produce assignments to those that remain valid and leave the remainders generic.
But as your type system gets fancier, and particularly in the presence of union types and subtyping, this search process can feel like "make whatever type judgements are necessary to make this program still compile". E.g. in code like
let x = new Set();
x.add('hello');
x.add(3); // oops, meant to add the string '3'
f(x);
The inferencer can just reason "oh apparently x is Set<number|string>", and "oh apparently f() operates over all kinds of sets, Set<{}>". And especially when there's never a more specific type for things to "bottom out" on (like say f just forwards the set elements to JSON.stringify(), which accepts both string and number already), nothing will ever reveal to you that you actually wrote a bug.But then meanwhile even in Haskell you run into cases where the inferencer wasn't generic enough, like https://wiki.haskell.org/Monomorphism_restriction , so it's not even clear cut that you want the inferencer to be smarter or dumber. As my coworker says: as a programmer you have to be able to basically run the inferencer in your head, and that becomes very hard when the inferencer gets very smart. (See the RxJS bug in the above blog post.)
Many people forget that the point of type inference is to eliminate uselessly redundant clutter, not to completely eliminate types from source code. A function is usually called many times, so keeping types on public API definitions and eliminating types from call sites and throwaway REPL code eliminates a huge amount of wasted typing (hah!) with near no loss of clarity.
During development, I like to keep my types unspecified until I'm confident that things have congealed properly. But before merging, I like to make sure and add type annotations to anything that's meant for public consumption.
Partially for readability and documentation. Partially because adding those annotations ensures that the type checker and I are on the same page. But mostly because those manual type annotations represent a promise that I, the programmer, have made about the current and future behavior of a certain chunk of code. Once those promises have been codified, then the type checker has my back and can help warn me if I'm about to break one of them with a careless change at some point in the future.
In Rust, inference is limited within functions. The language doesn't allow inferring the argument or return types of functions to avoid this kind of action at a distance.
The function API is just one of the many arbitrary places where one can limit inference and require users to provide types. In other languages the module boundary might also be an appropriate place to do that.
The github comment says: " (I might suggest the underlying problem in this code is relying on inference too much, but the threshold for "too much" is difficult to communicate to users.)"
The first part is exactly right; the second part is well established in the Rust language spec and Haskell style guides like http://www.cis.upenn.edu/~cis552/current/styleguide.html and https://kowainik.github.io/posts/2019-02-06-style-guide#func...
This way, when you write
const f = (a, b) => a + b
the compiler can tell you to write: const f => <T extends number|string>(a: T, b: T): T => a + b
or const f : <T extends number|string>(a: T, b: T) => T
= (a, b) => a + b
This would be effectively like GHC's typeholes, where the compiler will tell you what to write when you say f :: _
f a b = a <> b
except that rather than being an optional step by a developer, it's a mandatory standard.(Well, I don't think typescript infers that type for that function, but whatever it actually infers, that's what should be there in the error message.)
fn foo() { 42 }
in Rust, I get an error that says that `i32` (the type of `42`) is not of type `()` (unit), which is the return type of `foo`. So I can just change it to: fn foo() -> i32 { 42 }
instead. The same applies for generics, if I write: fn bar<T>(x: T, y: T) -> T { x + y }
I get the precise error that T does not implement the `Add<T>` trait. In this case the error is precise because there is only a trait in scope that supports `+`, but once there are many traits that would fit, which is rare, the compiler suggests some (often all of them). With that error I can just change that to: fn bar<T: Add>(x: T, y: T) -> T { x + y }
This is all done through local type inference within the function.Personally, I experience this quite often, e.g. in Java whenever arrow functions are heavily used, such as with streams.
It would be nice to have compilers report the whole inference chain somehow, just to be clear about all possible spots where things might be wrong. But I suppose that's difficult to visualize in a well human-readable way.
It's not. The type-checker must have constructed a call stack of inferred types in order to find the violation, so it simply has to print all the calls (source line and line number) and the types it deduced, and let the programmer (or IDE) compare that to the code in context and look for surprises.
1) Make types explicit (or generic) at any interface boundary
2) Periodically query the inferred types of things from my editor just to make sure they come out to what I expect
3) If an error message feels like it's in the wrong place or an inferred type isn't what it should be, progressively make things more explicit until the problem is resolved
But you're right, that's all very subjective and dependent on learned norms.
That's a very valuable insight, and a concern in a lot of languages with advanced inference!
The problem is exacerbated in Typescript though because it is fundamentally a practical, evolved layer over Javascript, with an unsound type system that likes to bail out to any.
Is this some TypeScript joke I'm too Hindley-Milner to understand?
It's an interesting goldilocks paradox likely only exacerbated by the size of Google's codebase and variety of developer code styles/inferencing preferences.
It also provides valuable documentation. You can usually work out what a function does from just its type (and quite often, that's all you have to work with).
which is a weakness in the culture of Haskell library authors and/or the ecosystem for contributing documentation patches.