We need both typings of the above interface, because when the data type(s) are erased as an input to a function which requires a (possibly union of) trait interface(s), e.g. Appendable or Enumerable, then there is no way to apply the first HKT typed interface because it requires the compiler knows the data type(s), e.g. Vec. For example, where C:Enumerable<T> is a type or possibly a union of types (such as Vec<T> \/ List<T>) that implement the trait Enumerable<T> in my proposed hypothetical programming language:
fn foo<T, C>(x: C) where T:Add+Nullable, C:Enumerable<T> {
fn f(prev: T, cur: T) {
if prev == null { return cur; }
else { return prev + cur; }
}
x.fold(null, f);
}
Tangentially (btw), I wish Rust would let me write the above in a more functional expression style:
fn foo<T, C>(x: C) where T:Add+Nullable, C:Enumerable<T> {
x.fold(null, (prev: T, cur: T) -> if !prev: cur else prev + cur );
}
Or even more concise:
fn foo<T, C>(x: C) where T:Add+Nullable, C:Enumerable<T> =
x.fold(null, (prev: T, cur: T) -> !prev ? cur : prev + cur )
But the possible encodings for the trait Add indicate the above code won't type check in my proposed hypothetical programming language. One possible encoding won't type check because T above has erased the data type(s) needed to compute Self:
trait Add {
fn plus(&self, &Self) -> Self;
}
Tangentially note that afair a Self type can be modeled with generics in a language with subtyping lower bounds (e.g. Scala) even if Self is not a keyword:
trait Add[SELF <: Add[SELF]] {
def +(x: SELF): SELF
}
And the other possible encoding won't type check because T above hasn't required the trait Coercion interface:
trait Add {
fn plus<A:Coercion<Self>>(&self, &A) -> Self;
}
But to write the trait bound on T we need higher-ranked typing (HRT) of A over a specific type parameter T as follows, not forall A over specific scopes(1)(2)(3):
fn foo<T, A, C>(x: C) where T:Add+Nullable+Coercion<A forall T>, C:Enumerable<T>
What the above would mean is that every data type of T must implement trait Coercion<A> for every value of A that corresponds to every data type in T. Well I am happy I was able to design above what is ostensibly the solution to this issue. Anybody know what this sort of HRT is canonically named and which canonically name type system does it inhabit? Or have I potentially (assuming it is sound) invented an entirely new type system variant?
Tangentially note that I am contemplating whether the above proposal for handling coercions via scoped traits rather than hard-coded in the language (as is afaik the case currently for Rust) is much more flexible and correct. Rust is afaik also not enabling implementing operators with traits?