4 ms·
Adding to this, there's a set of language features which use the type system to generate code. So, things like traits in Rust or Typeclasses in Haskell use the
by habitue 4y ago
Adding to this, there's a set of language features which use the type system to generate code. So, things like traits in Rust or Typeclasses in Haskell use the type system to infer which instance is being used and insert a dictionary of trait method implementations as the first argument to your polymorphic function. You can't really do this kind of thing if the compiler can't do `Type -> code` and is only verifying the types are consistent.
A pseudocode example is something like:
trait ToString for T {
fn toString(self: T) -> String;
}
impl ToString for number {
fn toString(self: number) -> String {
// implementation here
}
}
impl ToString for Point {
fn toString(self: Point) -> String {
return f"({self.x.toString()}, {self.y.toString()})";
}
}
fn printString<T: ToString>(t: T) {
print(t.toString());
}
Then when it generates code, it uses the inferred type information to generate different code:
let p = Point(1.0, 2.0);
printString(p);
// translated into
printString(implToStringForPoint, p);
let n = 2.0;
printString(n);
// translated into
printString(implToStringForNumber, n);
And then type inference becomes implementation inference, which is really powerful
- kaba0 4y agoBeside performance impact, how is it different than what is possible with virtual method (dyn dispatch)?
- svieira 4y agoOne jump vs. multiple pointer dereferences.
- munificent 4y agoVirtual dispatch makes it much harder for an optimizing compiler to inline method calls, so there is a significant performance hit even for callsites that do end up always calling the same method.