Re: Default args in custom constructor

2015-09-05 Thread Philip Hazelden
Oh, I'd been intending to explore that before sending but forgot. Thanks.

I currently think that's the best alternative to duplicating defaults, but
still more verbose and less intuitive than I'd hope for.

On Sat, Sep 5, 2015 at 12:57 AM Timo Paulssen  wrote:

> Have you considered hash flattening into argument lists yet?
>
> method new(Int $a) {
> my %args;
> with $a { %args<$a> = $a }
> self.bless(|%args);
> }
>
> Does that help you forward at all?
>   - Timo
>


Re: Default args in custom constructor

2015-09-04 Thread Timo Paulssen
Have you considered hash flattening into argument lists yet?

method new(Int $a) {
my %args;
with $a { %args<$a> = $a }
self.bless(|%args);
}

Does that help you forward at all?
  - Timo


Default args in custom constructor

2015-09-04 Thread Philip Hazelden
Suppose I have a class with a default attribute

class Foo { has Int $.a = 1; }

Now I want to write a custom constructor for it, with either `Foo.new()` or
`Foo.new(3)` doing the obvious thing. Here's one way to do it:

multi method new(Int $a = 1) { self.new(:$a); }

but this duplicates the default. Here's another:

multi method new() { self.new; }
multi method new(Int $a) { self.new(:$a); }

but this becomes horrible outside of the trivial cases.

I'm wondering if there's an idiomatic way to handle this without
duplicating the default. I think what I really want is something that says
"if $a is defined, then pass the named argument :$a; otherwise, pass
nothing". Something along the lines of

self.new(:a($a // Slip))

would be pretty good, except that Slip doesn't work like that, at least not
currently.

Another way to solve the same problem might be something like

multi method new(Int $a = Foo.^defaults<$a>) { self.new(:$a); }

if there was an easy way to access a class's variable defaults. (Is there
one that I don't know of?)

This isn't necessarily a big deal - right now I'm happy to just duplicate
my defaults - but it seems like something that's going to be a minor
annoyance in a lot of places.