Predicate Dispatch

Okay, since I’ve spent the whole damn day talking about other people’s languages, let me tell you something that I would give a lot of thought to if I were designing a language. Consider C# 3.0 extension syntax:

static void Foo(this String s){ … }
static void Foo(this Int32 i) { … }

s = “hello”;
i = 42;
s.Foo(); //resolves to Foo(this String s)
i.Foo();  //resolves to Foo(this Int32 i)

Now consider:

static List Sort(this List where this.Length < 1000000) { … }
static List Sort(this List where this.Length >= 1000000) { … }

Or:

static Double SquareRoot(this Double i where i >- 0) { … }
static Complex SquareRoot(this Double i where i < 0) { … }

Or:

static int Minimum(this TreeNode where treeNode.left.InstanceOf(EmptyNode){ return this.data; }
static int Minimum(this TreeNode) { return this.left.Minimum(); }

This idea of dispatching not just on the type of this, but on more complex (and dynamic) conditions, is called “predicate dispatch.” Putting aside the specifics of syntax, I think that predicate dispatch is to object dispatch what unit testing is to explicit typing: a more general and more domain-specific alternative that provides more flexibility, although with potentially serious runtime implications. But maybe not as much as you’d think.

Note the similarity to COmega’s chords:

public class Buffer {  
  public async Put(string s);  
  public string Get() & Put(string s) { return s; }

Calls to Buffer.Get() block until at least one call to Buffer.Put() has concluded, and then Get() actually has access to the s parameter of Put().

An abstraction that increases structural flexibility, allows domain-specific flexibility a la unit testing, and might address concurrency? Me likey.