Hacker News new | ask | show | jobs
by b2gills 2741 days ago
Note that there was no need to actually create an infix operator, as you can use any code as an infix operator if you surround it with `[&( )]`.

    say $filter «[&(  -> $l, $r { $l and $r }  )]» $source
Golfing it down a bit, the shortest I was able to get was

    say $filter «[&(   &[and]   )]» $source;
The `&[and]` references the infix `and` operator.

I think the reason the following doesn't work that way is that `and` is too thunky.

    say $filter «and» $source;
    say $filter «[and]» $source; # identical to previous line
(Note that `and` is supposed to be thunky, so that isn't a bug.)

---

I personally would write this:

    sub infix:<l-when-r> -> $_, $r {
      # note that the value to be matched with must be in $_
      # prior to using the `when` keyword.
      # it was done in the signature for conciseness

      $_ when $r
    }
Then the conditions can be code objects, regexes (which are a form of code object in Perl6), or literals. (I tried to get it to work with bare Junctions, but I was unable to get the `«»` part to pass it into the operator.)

It does mean that you have to use `True` rather than `1`.

    my $filter = {
        f2 => True,
        f3 => *.contains('data'),
        f5 => {
            f6 => /data/,
        },
        f10 => * == (0 | 1 | 42), # only match these values
        f11 => 42, # only match something equal to 42
    }

    say $source «l-when-r» $filter;