A Briefer Syntax for Using Concepts

Mason McGill via Digitalmars-d digitalmars-d at puremagic.com
Wed May 7 06:53:02 PDT 2014


On Wednesday, 7 May 2014 at 11:57:51 UTC, w0rp wrote:
> Here is a question, is it possible for D, or any future 
> language, to eventually take something like this...
>
> void foo(InputRange)(InputRange range) 
> if(isInputRange!InputRange);
>
> ...and to instead be able to write it like this?
>
> void foo(InputRange range);
>
> Where the latter expands into something like the former, and 
> InputRange is not a type. How to declare such a thing in the 
> first place doesn't matter that much. There are many ways that 
> could be done. I'm just wondering if the above is possible at 
> all.

I think Julia does something like this, under the hood. Julia 
functions are instantiated once for every concrete argument type 
tuple they are invoked with:

   f(x) = x + 2
   f(5)         # Instantiation for Int64
   f(5.0)       # Instantiation for Float64

The assembly for these instantiations can be inspected by calling 
`code_native`. This works well for Julia because its runtime and 
type system are designed around being able to do this (JIT 
compilation, multiple dispatch, duck typing, immutable types).

Programmers try to use run-time and compile-time polymorphism for 
the same thing: expressing operations on abstract types. But, 
each approach has its own advantage (CT: speed; RT: dynamic 
dispatch). I think the key insight is that the optimal 
implementation (RT vs. CT) depends only on how the generic 
function is used, not how it is defined. So, the choice of 
implementation can, in theory, be left up to a 
sufficiently-sophisticated runtime/JIT compiler. This seems to be 
what Julia has done (possibly along with some other Lispy 
languages; I'm not sure).

However, this scheme can't entirely replace D-style templates 
(e.g. pattern matching). So, Julia still lets you define 
templates (which they call "objects with static parameters").

It would be great to have something like this in D (with 
compile-time semantics, of course).


More information about the Digitalmars-d mailing list