From Reddit
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Wed Jun 17 08:17:35 PDT 2009
bearophile wrote:
>> Some comments are patently false (such as the one that you must compile with dmc to call C functions on Windows).<
>
> Is this true? I have seen many times people here answer that code has to be compiled with DMC, etc. If I am wrong I'll fix the text.
I thought this was pretty much true for DMD-compiled code, unless either
function is in a DLL or some kind of object file converter is used. (Or an
ancient non-DMC C compiler that still produces OMF, I suppose)
Those are a lot of conditions, of course :P.
>> Some are ignorant (the author concluded that dmd can't optimize tail recursion by trying it with the non-tail-recursive factorial function; and I took the time to explain him!).<
>
> If I compile this D2 program with DMD:
>
> import std.stdio: printf;
> import std.conv: to;
>
> int sum(int[] a, int start=0) {
> if (start >= a.length)
> return 0;
> else {
> return a[start] + sum(a, start+1);
> //auto b = a[start];
> //return b + sum(a, start+1);
> }
> }
>
> void main(char[][] args) {
> int n = args.length > 1 ? to!int(args[1]) : 1;
> auto a = new int[n];
> foreach(i, ref x; a)
> x = i;
> printf("%d\n", sum(a));
> }
>
>
> This is the cleaned up code I obtain:
>
[snip code with recursive call instead of loop]
>
>
> LDC is almost able to turn that tail-call into a loop (you have to split the final expression in two parts, I don't know if in the meantime such limit has being lifed), and GCC is able to.
He's right though; the code isn't properly tail recursive (it performs an add
after the recursion). However, it can be *made* tail recursive by introducing an
accumulator, which is something LLVM does here[1].
[1]: It currently does not realize the array load can be done before the
function call, but I submitted a patch to LLVM for that. (This is why it
currently needs to be split up, so that LDC emits the load before the function call)
More information about the Digitalmars-d
mailing list