5 ms·
This looks a lot like Rust's match blocks (which were inspired by pattern matching in ML languages). It's nice to see pattern matching constructs come to more l
by CDSlice 7y ago
This looks a lot like Rust's match blocks (which were inspired by pattern matching in ML languages). It's nice to see pattern matching constructs come to more languages.
- lizmat 7y agoBut, this has really not a lot to do with pattern matching. Please see my comment at https://www.reddit.com/r/perl6/comments/bvhzwh/perl_6s_given_switch_on_steroids_matéu/eppm0oz/ https://www.reddit.com/r/perl6/comments/bvhzwh/perl_6s_given...
- agumonkey 7y agothe condition tree flattening reminds me of pattern matching compilation though
- Sharlin 7y agoSurely it has everything to do with pattern matching? A C-style switch statement is an extremely primitive version of pattern matching, and in the article the flattened equivalent of the nested switch structure is just tuple destructuring and matching, just like in Rust I could write match (foo, bar, baz) { (1, 2, 3) => something(), (3, 2, 1) => somethingelse() }
- nemetroid 7y agoFrom that explanation, it sounds very similar to pattern matching in general, and Erlang's case statement in particular. Would you care to elaborate?
- b2gills 7y agoRust'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.)