More on the D Programming Language

Joe Gregorio

I've spent a little more time poking around D and I really like what I see. My appreciation is influenced by the languages posture, which is a pragmatic focus on being a productive programming language. Like I mentioned previously closures were just added. Here is an example of a numerical derivative:

import std.stdio;

alias double delegate(double) fn;

fn derivative(fn f, double dx) {
    double deriv(double x) {
      return (f(x + dx) - f(x)) / dx;
    };
    return &deriv;
}

void main() {
    double xcubed(double x) {
      return x*x*x;
    }
 
    fn f = &xcubed;
    auto df = derivative(f, 0.01); 
    writefln(df(1.0));
    auto ddf = derivative(df, 0.01); 
    writefln(ddf(1.0));
}

One of the things that makes it different, particularly from C++, is pushing work off of the programmer and onto the compiler. For example, all non-static, non-template member functions are virtual and it's up to the compiler to do the analysis and only generate the vtable entries where they're needed. The same thing applies to strong typing, it is leveraged to make life easier, ala auto and the foreach construct. In the code below the type of the variable four is deduced from it's context:

import std.stdio;

double f(double x) {
   return x * 2.0;
}

void main() {
   auto four = f(2.0);
   writefln(four);
}

In the following example the type of the variable i is determined by the compiler.

import std.stdio;

void main() {
  int[] myarray = [1,2,5,12];
 
  foreach (i; myarray) {
    writefln(i);
  } 
}

D takes inspiration from modern languages like Python, for example, traits handle many of your introspection needs, and the handling of properties is amazingly rational, allowing you to expose public properties now, and replace them with setters and getters later if the need arises without changing the calling code. D isn't sitting still either, here are slides (pdf) from the recent D conference which show that hygienic macros are on their way, in case you're sitting at home with your language score card, and if you're thinking about parallel systems there's two slides (pp17-18) which are a bit light on details, but they mention "Pure Functions" and their being memoized, scheduled and automatically parallelized. Oh yeah, did I mention that you can call C functions? I think D's got legs and it'll be interesting to see where it goes.

I've been programming in D since just before it hit 1.0 this year, and the biggest appeal for me is the pragmatic angle. In common with other community developed languages like Python and Ruby, it feels like the language is evolving to help the programmer. While on the other hand industry backed languages like C# and Java feel like they're adding features to appeal to the "enterprise". And the Digital Mars D compiler is amazingly zippy - it leaves pretty much every other C++ compiler in the dust.

Posted by Dan V. on 2007-11-11

comments powered by Disqus