std.algorithm - notes

bearophile bearophileHUGS at lycos.com
Thu Mar 6 15:05:46 PST 2008


Jarrod:
> I disagree. D is a straightforward language. Adding python list 
> generation adds a big 'special case' scenario. Wrapping a for loop inside 
> square brackets? Hmm I don't think that's better than using map/filter. 

For more of your amusement, the following is a little Python program coming from here:
http://wordaligned.org/articles/why-python-programmers-should-learn-python
That refers to the last pages of this document:
http://www.keithbraithwaite.demon.co.uk/professional/presentations/2003/ot/why_learn_python.pdf

My Python version:

def inverter(n):
    n2txt = "zero one two three four five six seven eight nine".split()
    txt2n = dict((digit, str(i)) for i, digit in enumerate(n2txt))
    if isinstance(n, basestring):
        return int("".join(txt2n[p] for p in n.split()))
    else:
        return " ".join(n2txt[int(d)] for d in str(n))

print inverter(752) # prints: seven five two
print inverter("seven five two") # prints 752


My (working) D translation (with my d libs):

import std.string, d.func, std.conv, d.string;

template Inverse(T) {
    static if(IsType!(T, byte, ubyte, int, uint, long, ulong))
        alias string Inverse;
    else
        alias long Inverse;
}

Inverse!(T) inverter(T)(T n) {
    auto n2txt = "zero one two three four five six seven eight nine".split();
    auto txt2n = dict(zip(n2txt, map(&format, xrange(10)) ));
    static if(IsType!(T, byte, ubyte, int, uint, long, ulong))
        return map((char d){return n2txt[toInt(d~"")];}, str(n)).join(' ');
    else
        return toInt(map((string p){return str(txt2n[p]);}, n.split()).joinArr());

}

void main() {
    putr(inverter(752));
    putr(inverter("seven five two"));
}

As you can see the D version uses map() and various anonymous functions that clutter code making it not much readable, despite those many helpers. In the end I am probably not going to use such D code, while in Python that code despite being a bit slow is almost acceptable.

Bye,
bearophile



More information about the Digitalmars-d mailing list