A little thing about function templates / Ruby

Jarrett Billingsley kb3ctd2 at yahoo.com
Mon Feb 12 08:02:04 PST 2007


"mike" <vertex at gmx.at> wrote in message news:op.tnm59miynxkcto at zimmermoos...

Uhh, ignore the other post.

--------------------------------------------------------
I'm currently finally learning templates (never understood them in C++). I
know this isn't possible, but is something like that maybe in the works
for D 2.0? I suspect that something like this has already been proposed,
but since I'm just now starting to grok how Ruby works ... anyway:

' void each(T[] array, void delegate(T) dg)
' {
'     foreach(item; array) dg(item);
' }
'
' [1, 2, 3].each(void delegate(int x) { writefln(x); });

Don't know how the principle is called. I mean that
using-the-"."-to-say-that-this-should-be-the-first-argument-thing. Would
be nice to "inject" fake member functions to classes this way.
--------------------------------------------------------

Actually, this is possible ;)

void each(T)(T[] array, void delegate(T) dg)
{
    foreach(item; array) dg(item);
}

void main()
{
    [1, 2, 3].each(delegate void(int x) { writefln(x); });
}

This is an undocumented feature, being able to call functions which take 
arrays as their first argument as if they were member functions.

--------------------------------------------------------
And maybe using "->" as a shortcut for that whole thing, so it looks a bit
like Ruby with this syntax:

' [1..3].each -> (x) { writefln(x); }

The compiler could infer the types involved, if the delegate should return
something, etc. That would be major.
--------------------------------------------------------

You can already do delegate return type inference:

[1, 2, 3].each((int x) { writefln(x); });

--------------------------------------------------------
And finally two other things from
Ruby I'd like to see in D:

' x, y = getCursorLocation();  // a must, really!
' foo() unless (doNotCallFoo); // those statement modifiers seem very
logical to me

Ruby syntax still looks ugly to me, and I don't think I'll ever like that,
but I absolutely love those features I mentioned above :)
--------------------------------------------------------

Multiple return types would be kind of nice.. they could probably be handled 
as implicit 'out' parameters.  I never really liked the "postfix 
conditional" syntax though.  It seems to me like it'd be easy to miss what's 
going on. 





More information about the Digitalmars-d mailing list