Like getClass()

bearophile bearophileHUGS at lycos.com
Sat Sep 27 11:33:29 PDT 2008


I have solved my original problem :-) I show here the code for reference:

This is the original Python code, that sorts a python list (array) of objects according to their class:


class Circle:
    def __init__(self, x, y, radius):
        self.x = x
        self.y = y
        self.radius = radius
    def draw(self):
        print "Drawing Circle at (%s,%s) with radius %s" % (self.x, self.y, self.radius)

class Square:
    def __init__(self, x, y, width):
        self.x = x
        self.y = y
        self.width = width
    def draw(self):
        print "Drawing Square at (%s,%s) with width %s" % (self.x, self.y, self.width)

if __name__ == "__main__":
    order = [Circle, Square] # the order in which to draw the shapes
    shapes = [Circle(1,1,5), Square(2,4,3), Circle(3,3,7), Square(4,2,4)]
    shapes.sort(key=lambda s: order.index(s.__class__))
    for shape in shapes:
        shape.draw()




This is my best D translation so far, I am happy enough:

import std.stdio: writefln;
import d.func: sort, findPos;

interface Shape {
    void draw();
}

class Circle : Shape {
    float x, y, radius;
    this(float x, float y, float radius) {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }
    void draw() {
        writefln("Drawing Circle at (%s,%s) with radius %s", x, y, radius);
    }
}

class Square : Shape {
    float x, y, width;
    this(float x, float y, float width) {
        this.x = x;
        this.y = y;
        this.width = width;
    }
    void draw() {
        writefln("Drawing Square at (%s,%s) with width %s", x, y, width);
    }
}

void main() {
    auto order = [Circle.classinfo, Square.classinfo]; // the order in which to draw the shapes

    auto shapes = [cast(Shape)(new Circle(1,1,5)), new Square(2,4,3),
                   new Circle(3,3,7), new Square(4,2,4)];

    shapes.sort((Shape s){ return findPos((cast(Object)s).classinfo, order); });

    foreach (shape; shapes)
        shape.draw();
}

It uses sort() and findPos(), but similar functions are probably present in Tango too, the first sorts an array according to a key function, and the second gives the index of an item into an iterable or -1 if absent.

If the 'order' array becomes too much long it can of course be replaced by an associative array, that gives a faster lookup.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list