My presentation at Oscon last Thursday

bearophile bearophileHUGS at lycos.com
Sat Jul 24 11:30:50 PDT 2010


Walter Bright:
> http://assets.en.oreilly.com/1/event/45/The%20D%20Programming%20Language%20Presentation.pdf

I'm currently reading many other PDF/PPT from other conferences too.

In your RAII example you are doing something that's scary, mixing C heap allocations with D GC heap allocations with C free. This is a program based on your code:

import std.c.stdlib: malloc, free;
struct Buffer {
    this(size_t s) {
        buf = malloc(s)[0 .. s];
    }
    this(this) {
        buf = buf.dup;
    }
    ~this() {
        free(buf.ptr);
    }
    void[] buf;
}
void main() {
    auto b1 = Buffer(100);
    auto b2 = b1;
}

But I think this is better:

import std.c.stdlib: malloc, free;
struct Buffer {
    this(size_t s) {
        buf = malloc(s)[0 .. s];
    }
    this(this) {
        void* newbuf = malloc(buf.length);
        newbuf[0 .. buf.length] = buf[];
        buf = newbuf[0 .. buf.length];
    }
    ~this() {
        free(buf.ptr);
    }
    void[] buf;
}
void main() {
    auto b1 = Buffer(100);
    auto b2 = b1;
}


This is your example for the functional style:

pure sum_of_squares
 (immutable double[] a)
{
    auto sum = 0;
    foreach (i; a)
        sum += i * i;
    return sum;
}


But I think this is better, the function name follows the D style page you have written and the 'sum' is not an integer value:

pure double sumOfSquares(double[] arr) {
    double sum = 0.0;
    foreach (item; arr)
        sum += item * item;
    return sum;
}


For a functional-style piece of code I'd like to write:

import std.algorithm: reduce;
pure double sumOfSquares2(double[] arr) {
    return reduce!q{a + b * b}(0.0, arr);
}

But it seems reduce isn't pure yet...

The page on compilers seems to show that both DMD and LDC are able to compile the given examples, but LDC is mostly D1 only for now...

Bye,
bearophile


More information about the Digitalmars-d mailing list