Match, case with logic? - scala

def searchEquipmentCategory(category: String) = Action {
val equipment = Equipment.searchByCategory(category)
equipment.size match {
case 0 => NotFound(views.html.helpers.notfound("Equipment not found for category :" + category))
case (_ > 0) => Ok(views.html.equipment.index(equipment, capitalize(category)))
}
}
Is it possible put logic in a match case statement?
I've searched everywhere and can't find any documentation. I just want to have if the case is 0 do one thing if the number is over 0.
Using the _ default works fine in that situation, but what if I wanted to do 3 things?
if number == 0
if the number is between 1 and 10
if the number is between 11 and 20
Maybe I'm trying to do too much with case.
Thanks for the help.

case i if i > 0 => Ok( ... )
So to distinguish between 0, 1 to 10 and 11 to 20:
case 0 =>
case i if i >= 1 && i <= 10 =>
case i if i >= 11 && i <= 20 =>
But then I guess an if-else if-else block is more readable.

This is called guards:
case x if (x > 0) => OK ...

Related

Conversion of Marks into GPA using pattern matching in scala

I am trying to write Scala function that takes marks and return GPA based on defined criteria. I am using pattern matching but pattern matching works if case has single value like case 50 => 1, but I am unable to get desired results as i want, like return GPA 1 if marks are equal to or greater than 50 and less than 58. My code is here.
def convertor(marks : Int) : Int = marks match {
case marks if marks < 50 => 0
case marks if marks >= 50 && marks < 58 => 1
case marks if marks >= 58 && marks < 70 => 2
case marks if marks >= 70 && marks < 85 => 3
case marks if marks >= 85 => 4
}
Every case creates a new temporary variable which, in this case, you don't actually need. So you could do this:
def convertor(marks : Int) : Int = marks match {
case _ if marks < 50 => 0
case _ if marks >= 50 && marks < 58 => 1
case _ if marks >= 58 && marks < 70 => 2
case _ if marks >= 70 && marks < 85 => 3
case _ if marks >= 85 => 4
}
Or, as #LeoC aptly points out:
def convertor(marks : Int) : Int = marks match {
case _ if marks < 50 => 0
case _ if marks < 58 => 1
case _ if marks < 70 => 2
case _ if marks < 85 => 3
case _ => 4
}
But that's little better than sequencing if/else if tests. I'd be inclined to try something like this:
def convertor(marks : Int) : Int =
Seq(50, 58, 70, 85, Int.MaxValue).indexWhere(marks < _)

Nested pattern matching in Scala

I'm new to Scala and I'm trying to understand how pattern matching works. So I wrote this basic code, which returned the expected result:
def test(choice: Int): String = choice match {
case x if x > 0 && x%2 == 0 => "positive even number"
case x if x > 0 && x%2 != 0 => "positive odd number"
case 0 => "null"
case x if x < 0 && x%2 == 0 => "negative even number"
case x if x < 0 && x%2 != 0 => "negative odd number"
}
Now I'm trying to do something a little more elaborate:
def test(choice: Int): String = choice match {
case x if x%2 == 0 => x match {
case y if y > 0 => "even and positive number"
case y if y < 0 => "even and negative number"
}
case 0 => "null"
case x if x%2 != 0 => x match {
case y if y > 0 => "odd and positive number"
case y if y < 0 => "odd and negative number"
}
}
But it failed. Here's the error message on the console:
scala> def test(choice: Int): String = choice match {
|
| case x if x%2 == 0 => x match {
| case y if y > 0 => "even and positive number"
| Display all 600 possibilities? (y or n)
[...]
| if y < 0 => "even and negative number"
<console>:5: error: '(' expected but identifier found.
if y < 0 => "even and negative number"
^
[...]
Can somebody tell me what I'm doing wrong and give me some details about what I misunderstand about Scala in general and the match method in particular.
It compiles for me. The order of cases doesn't matter for the success of compilation (however, the case 0 branch will never match, because case x if x%2==0 matches x=0. You may want to make the case 0 branch the first one)
I believe your problem is because of using tabs instead of spaces in the terminal.
If you use this code in a file in a project, it'll compile just as well. If you want it to work in the console, you can either:
convert the tabs to spaces before pasting the code
enter paste mode in the REPL using the :paste command, paste the code and exit paste mode with Ctrl-D (or whatever the REPL tells you the combination is - that's the one on Mac).
In your first code, you test for x>0 in the first 2 cases, then for 0 itself.
In the second code, you don't test for x>0, but x%2 == 0 which already matches for x = 0, and a second, outer match isn't considered.
If you put the explicit 0 match on top, it might work, but I didn't look for a second error and only matched for the first error I could find. :)

Scala: simplify case with comparison

Let's say, I have the following code snippet:
val num = Future.successful(10)
num map {
case n if n > 0 => // do something
case _ // do something
}
My question is: can I simplify case n if n > 0 somehow?
I expected that I can write something like:
case _ > 0 => // do something
or with explicitly specified type (although we know that Future has inferred type [Int]):
case _: Int > 0 => // do something
Can this code be simplified somehow?
You can't simplify case n if n > 0 => ....
Every case clause in a pattern match needs to have a pattern and (optionally) a guard.
The syntax you are referring to (_ > 0) is only valid in lambdas, but there's no similar special syntax for case clauses.
If you want to simplify the guard, you can filter the Future a priori:
val num = Future.successful(10).filter(_ > 0).map { nat =>
}
Otherwise, you can keep the guard and use Future.collect:
val num = Future.successful(10).collect {
case n if n > 0 => // do something
}
One important thing to note is that if the partial function is not defined for the value which returned (i.e for your case -1) then the resulting future will be a Failure containing a NoSuchElementException.
Other than these options, you'll need the guard. I don't see any syntactically shorter way to express it.

Method evaluation not behaving as expected

Below code calculates the total a fibonacci sequence to a particular number.
But a StackOverFlow exception is being thrown. Why is this exception being thrown as I am checking
for 0 within the function ?
object fibonacci extends Application {
def fibonacci(i : Int) : Int = {
println(i)
if(i == 0) 0
if(i == 1) 1
fibonacci(i - 1) + fibonacci(i - 2)
}
fibonacci(3)
}
Error :
scala> fibonacci(3)
3
2
1
0
-1
-2
-3
-4
-5
-6
-7
-8
-9
.......
scala> fibonacci(3)
java.lang.StackOverflowError
at .fibonacci(<console>:10)
at .fibonacci(<console>:10)
at .fibonacci(<console>:10)
at .fibonacci(<console>:10)
def fibonacci(i : Int) : Int = {
println(i)
if (i == 0) 0
else if (i == 1) 1
else fibonacci(i - 1) + fibonacci(i - 2)
}
Without those else you're not stopping when you reach 0 or 1.
Scala will automatically evaluate the return value of a function to be the value of the last statement calculated (this is the reason you don't need the return keyword).
Without elses, your two if statements are stand-alone statements, but not the last statement in the function. They resolve to a value, but this value is not assigned to anything and so is thrown away and the function continues processing statements.
Putting elses in (as per #Marth's solution) ensures that you end the function with one single statement consisting of a single if-else chain. This whole statement (and hence, the function) evaluates to the result of whichever branch of the chain is selected and executed.
You can also acheive the effect you want using a match (which is also treated as one single statement):
def fibonacci(i : Int) : Int = {
println(i)
i match {
case 0 => 0
case 1 => 1
case _ => fibonacci(i - 1) + fibonacci(i - 2)
}
}

A way to write this more concise? Need to check if a number is under 0

val total_breaks = //a random number
total_breaks match {
case i if(i < 0) => chartTemplate.setAttribute("totalBreaks", 0)
case _ => chartTemplate.setAttribute("totalBreaks", total_breaks)
}
I was thinking there was a function in Scala that could shorten this. I thought min did this but I guess not. I can't seem to find documentation on min, max, etc.
Something like total_breaks.min(0). Display 0 if under 0 if not display total_breaks.
Also is there a way do something like this
(4 + 5) match {
case 0 => println("test")
case _ => println(_) //i need to display the number passed into match? Is this not possible?
}
If I do case i => println(i) is that the same as case _ => ? Is that the fallback?
There are methods min and max defined in GenTraversableOnce, and thus available on sequences. You can use them as:
scala> List(1, -4, 0).min
resN: -4
There is also min and max defined in RichInt, that work like operators on anything that can be converted to RichInt, typically your vanilla integers:
scala> -4 min 0
resN: -4
So if you want something that returns your number, say x if x is greater than 0 and 0 otherwise, you can write:
scala> x max 0
That means you can rewrite your pattern-matching as:
chartTemplate.setAttribute("totalBreaks", total_breaks max 0)
For your second question, _ and i are both valid patterns that will match anything. The difference is that in the first case you do not bind what you have matched to a variable. Using println(_) is wrong, though; as such, it corresponds to an anonymous function that prints its first argument. So if you don't want to repeat the expression (4 + 5), you should indeed write your pattern and code as:
case i => println(i)