How would you solve this 'interview' question in D?

Andrej Mitrovic andrej.mitrovich at gmail.com
Wed Jun 26 15:47:51 PDT 2013


On 6/26/13, Gary Willoughby <dev at kalekold.net> wrote:
> Just for a bit of fun, I saw this question posted on reddit the
> other day and wondered how *you* would solve this in D?
>
> http://stackoverflow.com/questions/731832/interview-question-ffn-n

Silly mathematicians, nobody said you had to make it performant.

import std.conv;
import std.string;
import std.stdio;

auto f(T)(T n)
{
    static struct S { int n; }

    static if (is(T == int))
        return S(n);
    else
        return to!int("-" ~ n.n.to!string.chompPrefix("-"));
}

void main()
{
    foreach (i; int.min .. int.max)
    {
        writefln("%s => %s", i, i.f.f);
    }
}


More information about the Digitalmars-d-learn mailing list