Skip to content

Commit

Permalink
Implement pred() and succ() for the Enumeration role
Browse files Browse the repository at this point in the history
These method will walk the enumeration in the declaration order.

Using Order as an example:
- Order::Same.succ is Order::More,
- Order::Same.pred is Order::Less.

Calling pred or succ on the boundaries will fail with X::OutOfBound.
Using the same example, Order::Less.pred fails with this X::OutOfRange:
"Decrement out of range. Is: Less, should be in Order::Less^..Order::More".
  • Loading branch information
book committed Sep 14, 2017
1 parent a8e0352 commit 2645a1e
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/core/Enumeration.pm
Expand Up @@ -32,6 +32,21 @@ my role Enumeration {
?? $x
!! self.^enum_from_value($x)
}

method pred() {
my @values := self.^enum_value_list;
my $index = @values.first( self, :k );
return $index <= 0
?? Failure.new( X::OutOfRange.new( what => "Decrement", got => self, range => @values[0] ^.. @values[*-1] ) )
!! @values[ $index - 1 ];
}
method succ() {
my @values := self.^enum_value_list;
my $index = @values.first( self, :k );
return $index >= @values.end
?? Failure.new( X::OutOfRange.new( what => "Increment", got => self, range => @values[0] ..^ @values[*-1] ) )
!! @values[ $index + 1 ];
}
}

# Methods that we also have if the base type of an enumeration is
Expand Down

0 comments on commit 2645a1e

Please sign in to comment.