zenscript
zenscript copied to clipboard
Delegation through type classes
I've been waffling about the expressive power of delegation for a while, so I wonder if we can express delegation as part of type classes (ordinarily, they sorta work like subclassing, or maybe reverse subclassing).
I'll start vague and let you guys correct me to get to a more formal solution. Basically, what I want to do is make it so you can change the traits implemented for a type.
Something like this (sorry for the pseudo-syntax, I haven't quite come to grips yet with proposed syntax):
// We have type A
type A
// And a trait B, which defines a method X
trait B {
x()
}
// We implement X for A
implement B for A {
x() { return "hello" }
}
// Type B delegates to generic T
type B<T> delegatesTo T
// We construct a variable b of type B<A>
let b = new B<A>();
// This works, because delegation means any traits defined for A can be used for B
x(b)
// We define a new type C, which has no traits implemented
type C
// We mutate variable b, so that it becomes type B<C>
b: B<C> = setDelegationTo(b, typeof C)
// This will now produce a compiler error, because method X is no longer defined for b
x(b) // won't compile
The reason why such a delegation scheme would be interesting is outlined in this paper: http://www.cs.cmu.edu/~aldrich/papers/rdl04.pdf
Comment removed, I realized it's unnecessary, code above edited.
Also, note that to delegate to a type, you need to reference a record of that type. Variable b would store a reference to a variable of type a. This is commonly called a prototype. How to specifically set this up, I didn't address yet in my example, assume for now that the constructor of B takes care of that and that setDelegationTo changes this reference to a different record. The focus is, for now, on the delegation typing part.