Explicitly named return values?

In Go ( and g ++? ) The following general idiom:

func sqr(x int) (n int, err error) {
    n = x * x
    err = nil
    return
}

(n int, err error)explicitly lists the name and type of return values. In my opinion there are many advantages to this, and I like it.


In Perl 6 we can:

my sub sqr (Int:D $x) returns Int:D {
    $x ** 2;
}

The return is implicit, which makes me inconvenient (we can make it explicit with return), but you may notice that the type of return is indicated (as well as the fact that it is Defined sub>).

It is not surprising that there is no obvious way to return a value explicitly by name, but I am curious because Perl (especially 6) is highly modified in every way, if there is a way to implement this. 1


1 However, hacking can be, but too bad, and I would not use it for "real" things.

+4
2

, .

, , , , - rw :

multi sub trait_mod:<is>(Routine:D \r, :$dynrv!) {
    r.wrap(-> | { my $*rv; callsame; $*rv })
}

multi sub trait_mod:<is>(Routine:D \r, :$pararv!) {
    r.wrap(-> |c { my $rv; callwith(|c, $rv); $rv })
}

sub double($x) is dynrv {
    $*rv = $x * 2;
    return 666; # discarded
}

sub triple($x, $y is rw) is pararv {
    $y = $x * 3;
    return 666; # discarded
}

say double 42;
say triple 42;

, , , ...


edit: , :

multi sub trait_mod:<is>(Routine:D \r, :@dynrv!) {
    r.wrap(-> | {
        my @rv = Nil xx @dynrv;
        my $*rv = Map.new(@dynrv Z=> @rv);
        callsame;
        @dynrv > 1 ?? @rv !! @rv[0];
    })
}

multi sub trait_mod:<is>(Routine:D \r, Int :$pararv!) {
    r.wrap(-> |c {
        my @rv = Nil xx $pararv;
        callwith(|c, |@rv);
        $pararv > 1 ?? @rv !! @rv[0];
    })
}

sub divmod($a, $b) is dynrv<d m> {
    $*rv<d> = $a div $b;
    $*rv<m> = $a mod $b;
}

sub plusmin($a, $b, $p is rw, $m is rw) is pararv(2) {
    $p = $a + $b;
    $m = $a - $b;
}

say divmod 14, 3;
say plusmin 14, 3;
+6

, , , , . -, Cat Go , (Int). Perl 6 Fail, &fail, , .defined // operator;

if $something_wrong {
  return fail "Dang!  Even the squaring function isn't working today."
}
else {
  return $x ** 2
}

, , ? , , ?
, (Int) -. , (Str), .Str, , .

return $x * $x but "Suprise!  Bet you weren't expecting that!"

, , . , (Int) .size;

return $x but role { has $.size = calculate_size() }

, , , , (Int) , ;

role Size { has UInt:D $.size = 0 }
subset MyInt of Int where Size;

sub sqr(Int:D $x, UInt:D :$size = 12) returns MyInt:D {
  return $x * $x but Size($size)
}

my $square5 = sqr(5);
say "5 squared is $square5 with size $square5.size()."
# prints: 5 squared is 25 with size 12.

S14 S12 - mixin

+3

Source: https://habr.com/ru/post/1626010/


All Articles