Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does D std lib include something like boost.fusion and boost.mpl?

I'm still evaluating if i should start using D for prototyping numerical code in physics.

One thing that stops me is I like boost, specifically fusion and mpl.

D is amazing for template meta-programming and i would think it can do mpl and fusion stuff but I would like to make sure.

Even if i'll start using d, it would take me a while to get to the mpl level. So i'd like someone to share their experience.

(by mpl i mean using stl for templates and by fusion, i mean stl for tuples.)

a note on performance would be nice too, since it's critical in physics simulations.

like image 377
kirill_igum Avatar asked Jan 11 '13 22:01

kirill_igum


1 Answers

In D, for the most part, meta-programming is just programming. There's not really any need for a library like boost.mpl

For example, consider the lengths you would have to go to in C++ to sort an array of numbers at compile time. In D, you just do the obvious thing: use std.algorithm.sort

import std.algorithm;

int[] sorted(int[] xs)
{
    int[] ys = xs.dup;
    sort(ys);
    return ys;
}

pragma(msg, sorted([2, 1, 3]));

This prints out [1, 2, 3] at compile time. Note: sort is not built into the language and has absolutely no special code for working at compile time.

Here's another example that builds a lookup table for Fibonacci sequence at compile time.

int[] fibs(int n)
{
    auto fib = recurrence!("a[n-1] + a[n-2]")(1, 1);
    int[] ret = new int[n];
    copy(fib.take(n), ret);
    return ret;
}

immutable int[] fibLUT = fibs(10).assumeUnique();

Here, fibLUT is constructed entirely at compile time, again without any special compile time code needed.

If you want to work with types, there are a few type meta functions in std.typetuple. For example:

static assert(is(Filter!(isUnsigned, int, byte, ubyte, dstring, dchar, uint, ulong) ==
              TypeTuple!(ubyte, uint, ulong)));

That library, I believe, contains most of the functionality you can get from Fusion. Remember though, you really don't need to use much of template meta-programming stuff in D as much as you do in C++, because most of the language is available at compile time anyway.

I can't really comment on performance because I don't have vast experience with both. However, my instinct would be that D's compile time execution is faster because you generally don't need to instantiate numerous templates. Of course, C++ compilers are more mature, so I could be wrong here. The only way you'll really find out is by trying it for your particular use case.

like image 98
Peter Alexander Avatar answered Oct 03 '22 08:10

Peter Alexander