Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Possible Output Types in Perl6

Tags:

raku

I'd like to make a function that returns either a Range or an any Junction made up of multiple Ranges.

Eg :

sub foo (Range $a, Range $b) {
  if $a.min <= $b.max && $b.min <= $a.max {
    ($a.min < $b.min ?? $a.min !! $b.min)..($a.max < $b.max ?? $a.max !! $b.max) 
  } else {
    ($a|$b)  
  }
}

Is there an easy way of adding a Type constraint to the sub to say it could return a Range or a Junction?

Thought's I've had include

  • Multi sub that does the checking in the where clause.
  • Subset Any.
  • Always return a junction and just use one() (But I'd like to keep Ranges of possible)

But if there's a simpler way that someone can think of.

like image 966
Scimon Proctor Avatar asked Jul 11 '18 12:07

Scimon Proctor


1 Answers

Just create a subset that accommodates both results, and use it as if it were a type.

Note that since a Junction is not a subtype of Any, you have to mark it as being Mu.
(Junction specifically can't be Any and work the way it does)

my subset Range-or-Junction of Mu where Range|Junction;
proto sub foo ( Range, Range --> Range-or-Junction ) {*}

multi sub foo (Range $a,Range $b where $a.min ~~ $b || $a.max ~~ $b --> Range){
  # note that this is wrong as it doesn't takes into consideration
  # :excludes-min or :excludes-max
  min($a.min,$b.min) .. max($a.max,$b.max)
}
multi sub foo (Range $a,Range $b --> Junction){
  $a | $b
}
like image 186
Brad Gilbert Avatar answered Nov 19 '22 08:11

Brad Gilbert