I started learning scala a few days ago and when learning it, I am comparing it with other functional programming languages like (Haskell, Erlang) which I had some familiarity with. Does Scala has guard sequences available?
I went through pattern matching in Scala, but is there any concept equivalent to guards with otherwise
and all?
case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .
Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.
Haskell guards are used to test the properties of an expression; it might look like an if-else statement from a beginner's view, but they function very differently. Haskell guards can be simpler and easier to read than pattern matching .
Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.
Yes, it uses the keyword if
. From the Case Classes section of A Tour of Scala, near the bottom:
def isIdentityFun(term: Term): Boolean = term match { case Fun(x, Var(y)) if x == y => true case _ => false }
(This isn't mentioned on the Pattern Matching page, maybe because the Tour is such a quick overview.)
In Haskell, otherwise
is actually just a variable bound to True
. So it doesn't add any power to the concept of pattern matching. You can get it just by repeating your initial pattern without the guard:
// if this is your guarded match case Fun(x, Var(y)) if x == y => true // and this is your 'otherwise' match case Fun(x, Var(y)) if true => false // you could just write this: case Fun(x, Var(y)) => false
Yes, there are pattern guards. They're used like this:
def boundedInt(min:Int, max: Int): Int => Int = { case n if n>max => max case n if n<min => min case n => n }
Note that instead of an otherwise
-clause, you simply specifiy the pattern without a guard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With