Wednesday, June 08, 2011

[lreysvsu] Magic expressions of a known type

Create a language extension such that wherever one can write a expression, one can write a special keyword, MAGIC, which, if there is exactly one symbol (function) in scope with the correct expected type as MAGIC, the compiler automatically rewrites it.  Of course, one can explicitly write (MAGIC::Foo->Bar) to constrain the type.  Dealing with an expression with multiple MAGICs might get hairy.  Also polymorphism.

A less ambitious version is not a language extension but a feature of an IDE.  Either way, IDE support is desirable to look up the function that will be called.

This saves the programmer from having to remember or look up exactly what the name of the function was.  Perhaps part of a large, unfamiliar library.

A more ambitious version has, if the compiler can uniquely derive the needed function out of existing functions, that works too.  Perhaps a different keyword, e.g., MOREMAGIC, to less surprise a programmer with an automatically derived function appearing out of nowhere.  If the compiler knows about a function with Foo->Bar and Bar->Baz, then it can synthesize Foo->Baz.  Another convenient use case I can think of is if you need to reorder or curry or uncurry the arguments to a function which takes arguments of distinct types.  The most extreme version synthesizes a function out of thin air if there can only be one function of the desired type, by a theorem or algorithm whose name I've forgotten. (Update: It's called Djinn.)

With this feature, one could permit anonymous top-level (or let-bound) functions, accessible only by the MAGIC mechanism.  The compiler complains if there are two anonymous functions of the same type.  This falls into the language design paradigm where a programmer ought not be forced to name things if he or she doesn't have to (lambda and point-free style are other examples).

2 comments :

Anders Kaseorg said...

We call it “type classes”.

class Magic a where magic :: a

instance Magic (Foo -> Bar) where magic foo = whatever

Neil Mitchell said...

Also look at Hoogle (which finds a type in the library) and Djinn (which derives a function from the type). Haskell is already full of MAGIC!