On Fri, Sep 14, 2018 at 10:52 PM Curt Tilmes <c...@tilmes.org> wrote:

>
>
> On Fri, Sep 14, 2018 at 10:42 PM ToddAndMargo <toddandma...@zoho.com>
> wrote:
>
>> When I said "yet", I presumed the a variable can be
>> redefined at will:
>>
>> $ p6 'my $x; say $x.perl;
>>           $x="abc"; say $x.perl;
>>           $x=Nil; say $x.perl;'
>> Any
>> "abc"
>> Any
>>
>> And that the receiving method only cares what you feed it
>> at the time it is called.
>>
>
> Your example doesn't limit the type.  If you limit the type, you'll get an
> error
> by assigning it something the type doesn't allow.
>
> my Int $x;
> $x = "abc"; # error can't put a string in an Int
>
> my Int:U $x;
> $x = 42; # error can't put a definite value in an Int:U
>
> my Int:D $x = 42;
> $x = Nil;   # error, can't undefine.
>
> You're only allowed to put in things that fit.  If an argument to a
> routine is limited, you can only pass in things that fit.
>

In other languages, we used to do things like:

int foo(char *str)
{
    if (str == NULL) { ... do something like error out or whatever...}
    ... do the stuff we really came here for ...
}

Who wants to do their own error checking?  Perl 6 lets you shape your
'front door' so only the right stuff gets through:

multi method foo(Str:D $str)
{
   ... just get right to it -- I know I won't (can't!) get something not
defined ...
}

If you want to do your own error handling, just throw in another multi to
handle the undefined case:

multi method foo(Str:U $str)
{
   .. do something else -- this only gets called when $str isn't defined...
}

You can even throw in a 'broader' undefined type:

multi method foo(Any:U $str)

If I call foo() with an "Int:U" or "Rat:U", it will call that one.

Curt

Reply via email to