4 ms·
Rust's match blocks appear to be less powerful than the smart-match feature in Perl6. Rust doesn't appear to allow arbitrary code in the condition. --- g
by b2gills 7y ago
Rust's match blocks appear to be less powerful than the smart-match feature in Perl6.
Rust doesn't appear to allow arbitrary code in the condition.
---
given 1 {
when (0 ≤ * ≤ 9) { 'digit' }
}
Expanding out the definition of the `when` above:
given 1 {
{
my $initial-result = (0 ≤ * ≤ 9); # get the result of the expression
my $result = $initial-result.ACCEPTS($_); # ask it if it accepts the topic
if $result {
succeed 'digit'
}
}
}
The condition part a `when` is just like the right side of the `smart-match` feature, and the `where` clause.
It does double code execution.
First as just a statement. (In this case the result is a lambda that will compare against `0` and `9`.)
Then it asks the result of the statement if it `ACCEPTS` the current topic value. (In this case it runs the lambda with topic as its argument.)
If the second level result is truish then `when` runs its block and calls `succeed` with its last value.
`succeed` throws a `CX::Succeed` control exception which the `given` catches.
---
This double code execution allows for a lot of flexibility. Also since smart-match asks the initial result if it `ACCEPTS` the topic, it gets to decide how it matches.
class Match-Always {
method ACCEPTS ( $ --> True ){}
}
class Match-Never {
method ACCEPTS ( $ --> False ){}
}
# match 50% of the time arbitrarily
class Match-Half {
method ACCEPTS ( $ --> Bool ){ Bool.pick }
}
given 1 {
when Match-Half { … }
when ( $_ == 1 ?? Match-Always !! Match-Never ) { … }
}
(Note that `True` works like `Match-Always` and `False` like `Match-Never`, so there is not a good reason to add those two types like I did.)