Friday, April 11, 2008

My favourite sugar

I've mentioned before that I've playing with D. Here's my current favourite feature in this language

//here's a trivial function
int add(int a, int b)
{
  return a + b;
}
//and the unusually neat way to call it:
int a = 10.add(20);

What happens here is that you can call any function as a method of any object, as long as the first parameter of the function is of the same type as the object you're "attaching" it to. Obviously, you omit the first parameter in the actual list of parameters when calling functions this way. It looks very Ruby-like in this example, and it can make code pretty clean-looking. Take this snippet for example:

import std.regexp;

void main()
{
  string s = "Hello World";
  int hello = find(s, "Hello");
  int world = find(s, "World");
}

It can be written like this:

import std.regexp;

void main()
{
  string s = "Hello World";
  int hello = s.find("Hello");
  int world = s.find("World");
}

The second syntax looks a lot cleaner and more modern, and there aren't any performance losses by using the dot syntax. Who needs fancy-pants classes? :)

Taking it a step further

D is a statically-typed language, but it does have a templating system, meaning you can write code that essentially looks like dynamically-typed code:

//some generic function
void add(T)(T object1, T object2)
{
  object1 += object2;
}
//some generic data type
alias int foo;
//some other generic data type
struct Point2D
{
  float x = 0;
  float y = 0;
  //overloading +=
  void opAddAssign(Point2D point)
  {
    x += point.x;
    y += point.y;
  }
}

foo n1 = 1;
foo n2 = 2;

n1.add(n2);//n1 == 3

auto p1 = Point(1, 1);
auto p2 = Point(2, 2);

p1.add(p2);//p1 = { x : 3 , y : 3 }

No comments:

Post a Comment