Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Scala have guards?

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?

like image 974
Teja Kantamneni Avatar asked Feb 15 '10 15:02

Teja Kantamneni


People also ask

What is case _ in Scala?

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 .

How does Scala pattern matching work?

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.

What is a guard in Haskell?

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 .

What is case class and pattern matching Scala?

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.


2 Answers

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 
like image 87
Nathan Shively-Sanders Avatar answered Sep 18 '22 19:09

Nathan Shively-Sanders


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.

like image 36
sepp2k Avatar answered Sep 20 '22 19:09

sepp2k