7

In scala, pattern match has guard pattern:

val ch = 23
val sign = ch match { 
    case _: Int if 10 < ch  => 65 
    case '+' =>  1 
    case '-' =>  -1 
    case  _  =>  0 
}

Is the Raku version like this?

my $ch = 23;
given $ch  {
    when Int and * > 10 { say 65}
    when '+' { say 1  }
    when '-' { say -1 }
    default  { say 0  }
}

Is this right?

Update: as jjmerelo suggested, i post my result as follows, the signature version is also interesting.

multi washing_machine(Int \x where * > 10 ) { 65 }
multi washing_machine(Str \x where '+'    ) { 1  }
multi washing_machine(Str \x where '-'    ) { -1 }
multi washing_machine(\x)                   { 0  }

say washing_machine(12);      # 65
say washing_machine(-12);     # 0
say washing_machine('+');     # 1
say washing_machine('-');     # -1
say washing_machine('12');    # 0
say washing_machine('洗衣机'); # 0
chenyf
  • 5,048
  • 1
  • 12
  • 35
  • What do you expect the Scala statement `case _: Int if 10 < ch => 65` to do? – Christopher Bottoms Apr 13 '18 at 12:55
  • 1
    I think you have to write it as `when $_~~Int and $_>10 {…}`. Note that `given` puts the value into `$_` within the block. – Brad Gilbert Apr 13 '18 at 16:55
  • 1
    @ChristopherBottoms it just return the number 65, may be the if statement is more complex, like `if 10 < ch < 120`. – chenyf Apr 14 '18 at 01:19
  • @Brad Gilbert you are right ^_^ – chenyf Apr 14 '18 at 05:36
  • _"Is the Raku version like this?"_ I obtain an erroneous answer when setting the value of `$ch` to `9`: the code returns `65` while the answer should be `0`. However the line `when (Int & (* > 10)) { say 65} ;` appears to correct. – jubilatious1 Mar 13 '21 at 02:18

4 Answers4

10

TL;DR I've written another answer that focuses on using when. This answer focuses on using an alternative to that which combines Signatures, Raku's powerful pattern matching construct, with a where clause.

"Does pattern match in Raku have guard clause?"

Based on what little I know about Scala, some/most Scala pattern matching actually corresponds to using Raku signatures. (And guard clauses in that context are typically where clauses.)

Quoting Martin Odersky, Scala's creator, from The Point of Pattern Matching in Scala:

instead of just matching numbers, which is what switch statements do, you match what are essentially the creation forms of objects

Raku signatures cover several use cases (yay, puns). These include the Raku equivalent of the functional programming paradigmatic use in which one matches values' or functions' type signatures (cf Haskell) and the object oriented programming paradigmatic use in which one matches against nested data/objects and pulls out desired bits (cf Scala).

Consider this Raku code:

class body { has ( $.head, @.arms, @.legs ) } # Declare a class (object structure).

class person { has ( $.mom, $.body, $.age ) } # And another that includes first.

multi person's-age-and-legs                   # Declare a function that matches ...

  ( person                                    # ... a person ...

    ( :$age where * > 40,                     # ... whose age is over 40 ...

      :$body ( :@legs, *% ),                  # ... noting their body's legs ...

      *% ) )                                  # ... and ignoring other attributes.

  { say "$age {+@legs}" }                     # Display age and number of legs.

my $age = 42;                                 # Let's demo handy :$var syntax below.

person's-age-and-legs                         # Call function declared above ...

  person                                      # ... passing a person.

    .new:                                     # Explicitly construct ...

      :$age,                                  # ... a middle aged ...

      body => body.new:
        :head,
        :2arms,
        legs => <left middle right>           # ... three legged person.

# Displays "42 3"

Notice where there's a close equivalent to a Scala pattern matching guard clause in the above -- where * > 40. (This can be nicely bundled up into a subset type.)

We could define other multis that correspond to different cases, perhaps pulling out the "names" of the person's legs ('left', 'middle', etc.) if their mom's name matches a particular regex or whatever -- you hopefully get the picture.

A default case (multi) that doesn't bother to deconstruct the person could be:

multi person's-age-and-legs (|otherwise)
  { say "let's not deconstruct this person" }

(In the above we've prefixed a parameter in a signature with | to slurp up all remaining structure/arguments passed to a multi. Given that we do nothing with that slurped structure/data, we could have written just (|).)

Unfortunately, I don't think signature deconstruction is mentioned in the official docs. Someone could write a book about Raku signatures. (Literally. Which of course is a great way -- the only way, even -- to write stuff. My favorite article that unpacks a bit of the power of Raku signatures is Pattern Matching and Unpacking from 2013 by Moritz. Who has authored Raku books. Here's hoping.)

Scala's match/case and Raku's given/when seem simpler

Indeed.

As @jjmerelo points out in the comments, using signatures means there's a multi foo (...) { ...} for each and every case, which is much heavier syntactically than case ... => ....

In mitigation:

  • Simpler cases can just use given/when, just like you wrote in the body of your question;

  • Raku will presumably one day get non-experimental macros that can be used to implement a construct that looks much closer to Scala's match/case construct, eliding the repeated multi foo (...)s.

raiph
  • 31,607
  • 3
  • 62
  • 111
  • 1
    Perl 6 signatures is Powerful. I will later update a version that use signatures. – ohmycloudy Apr 14 '18 at 06:08
  • 2
    That's a great answer. I see two potential problems with it, though. First, you actually have to declare the multis, while in Haskell and Scala they are simply statements. Second, there's no default way to declare a, well, default statement. Maybe using Slurpies, but I don't know if that covers it well. – jjmerelo Apr 14 '18 at 06:54
  • 1
    @jjmerelo The repeated `multi foo (...)` is indeed relatively verbose; perhaps macros will one day help. The simplest default does indeed use a slurpy -- `multi foo (|) {...}`. I've edited my answer in response to your feedback, thanks. (I've also written another answer.) – raiph Apr 14 '18 at 20:53
7

From what I see in this answer, that's not really an implementation of a guard pattern in the same sense Haskell has them. However, Perl 6 does have guards in the same sense Scala has: using default patterns combined with ifs. The Haskell to Perl 6 guide does have a section on guards. It hints at the use of where as guards; so that might answer your question.

jjmerelo
  • 22,578
  • 8
  • 40
  • 86
  • 2
    `multi` is awesome! seems comment doesn't support code, so I append my result under the question. – chenyf Apr 14 '18 at 05:52
6

TL;DR You've encountered what I'd call a WTF?!?: when Type and ... fails to check the and clause. This answer talks about what's wrong with the when and how to fix it. I've written another answer that focuses on using where with a signature.

If you want to stick with when, I suggest this:

when (condition when Type) { ... } # General form
when (* > 10 when Int) { ... }     # For your specific example

This is (imo) unsatisfactory, but it does first check the Type as a guard, and then the condition if the guard passes, and works as expected.


"Is this right?"

No.

given $ch {
  when Int and * > 10 { say 65}
}

This code says 65 for any given integer, not just one over 10!

WTF?!? Imo we should mention this on Raku's trap page.

We should also consider filing an issue to make Rakudo warn or fail to compile if a when construct starts with a compile-time constant value that's a type object, and continues with and (or &&, andthen, etc), which . It could either fail at compile-time or display a warning.


Here's the best option I've been able to come up with:

when (* > 10 when Int) { say 65 }

This takes advantage of the statement modifier (aka postfix) form of when inside the parens. The Int is checked before the * > 10.

This was inspired by Brad++'s new answer which looks nice if you're writing multiple conditions against a single guard clause.

I think my variant is nicer than the other options I've come up with in previous versions of this answer, but still unsatisfactory inasmuch as I don't like the Int coming after the condition.


Ultimately, especially if/when RakuAST lands, I think we will experiment with new pattern matching forms. Hopefully we'll come up with something nice that provides a nice elimination of this wart.

Really? What's going on?

We can begin to see the underlying problem with this code:

.say for ('TrueA' and 'TrueB'),
         ('TrueB' and 'TrueA'),
         (Int and 42),
         (42 and Int)

displays:

TrueB
TrueA
(Int)
(Int)

The and construct boolean evaluates its left hand argument. If that evaluates to False, it returns it, otherwise it returns its right hand argument.

In the first line, 'TrueA' boolean evaluates to True so the first line returns the right hand argument 'TrueB'.

In the second line 'TrueB' evaluates to True so the and returns its right hand argument, in this case 'TrueA'.

But what happens in the third line? Well, Int is a type object. Type objects boolean evaluate to False! So the and duly returns its left hand argument which is Int (which the .say then displays as (Int)).

This is the root of the problem.

(To continue to the bitter end, the compiler evaluates the expression Int and * > 10; immediately returns the left hand side argument to and which is Int; then successfully matches that Int against whatever integer is given -- completely ignoring the code that looks like a guard clause (the and ... bit).)

If you were using such an expression as the condition of, say, an if statement, the Int would boolean evaluate to False and you'd get a false negative. Here you're using a when which uses .ACCEPTS which leads to a false positive (it is an integer but it's any integer, disregarding the supposed guard clause). This problem quite plausibly belongs on the traps page.

raiph
  • 31,607
  • 3
  • 62
  • 111
4

Years ago I wrote a comment mentioning that you had to be more explicit about matching against $_ like this:

my $ch = 23;
given $ch  {

    when $_ ~~ Int and $_ > 10 { say 65}

    when '+' { say 1  }
    when '-' { say -1 }
    default  { say 0  }
}

After coming back to this question, I realized there was another way.
when can safely be inside of another when construct.

my $ch = 23;
given $ch  {

    when Int:D {
        when $_ > 10 { say 65}
        proceed
    }

    when '+' { say 1  }
    when '-' { say -1 }
    default  { say 0  }
}

Note that the inner when will succeed out of the outer one, which will succeed out of the given block.
If the inner when doesn't match we want to proceed on to the outer when checks and default, so we call proceed.

This means that we can also group multiple when statements inside of the Int case, saving having to do repeated type checks. It also means that those inner when checks don't happen at all if we aren't testing an Int value.

    when Int:D {
        when $_ < 10 { say 5 }
        when 10      { say 10}
        when $_ > 10 { say 65}
    }
Brad Gilbert
  • 33,846
  • 11
  • 78
  • 129