'new' class method

Bill Baxter wbaxter at gmail.com
Thu Oct 23 04:32:00 PDT 2008


On Thu, Oct 23, 2008 at 6:32 PM, bearophile <bearophileHUGS at lycos.com> wrote:
> In Python to create new instances of a class you use the normal function call syntax, this allows you to use them as factory functions:
>
> class C:
>    def __init__(self, id):
>        self.id = id
>    def __repr__(self):
>        return "<%s>" % self.id
> seq = map(C, [1, -5, 10, 3])
>
> That creates an array (list) of four objects.
>
> In D with a map() you can do something similar:
>
> import d.all;
> import std.string: format;
>
> class C {
>    int id;
>    this(int id) {
>        this.id = id;
>    }
>    string toString() {
>        return format("<%s>", this.id);
>    }
>    static C opCall(int id) {
>        return new C(id);
>    }
> }
> void main() {
>    auto seq = map((int id){return new C(id);}, [1, -5, 10, 3]);
>    putr(seq);
> }
>
> You can use the opCall method in a more direct way:
>
>    auto seq2 = map(&(C.opCall), [1, -5, 10, 3]);
>    putr(seq2);
>
> But probably even better is to replace the current new syntax with a class method that creates the instances (I think the Ruby language has such syntax):
>
>    auto seq3 = map(C.new, [1, -5, 10, 3]);
>    putr(seq3);

That would be  map(&(C.new), [1,-5,10,3]); wouldn't it?

> With that normal code like:
>
> new Foo(10, 20)
>
> becomes:
>
> Foo.new(10, 20)
>
> Not a big change but allows a more functional style of coding.

I like it.   Can we get rid of delete's specialness too?

Maybe just    delete(anInstance);
Make it like a normal function too.   Enabling things like

   map(&delete, [obj1, obj2, obj3])

--bb



More information about the Digitalmars-d mailing list