Reputation: 14309
I have the following code which works using a if-then-else ladder:
val test: Array[Array[Int]] = ...
val dim = 3
if (dim < test.length - 1) {
1
} else {
0
}
casting it as pattern matching I attempt:
val dim = 3
val maxDim = test.length - 1
dim match {
case _ < maxDim => {
1
}
case _ => {
0
}
}
but this produces multiple errors ... how can I do it as a pattern matching?
UPDATE: another attempt would be
dim match {
case maxDim => 0
case _ => 1
}
but doesn't work either
Upvotes: 0
Views: 201
Reputation: 40500
test.lift(dim).fold(0){ _ => 1}
This is not pattern matching, but the whole point is that you don't need pattern matching in this case.
Explanation: your if-then
thingy is basically testing whether the index is valid for an array, and returns 1 if it is, and 0 if it isn't (I am assuming, the lack of test for negative values was an oversight, and not an intentional feature).
Collections in scala are PartialFunctions
from Int
to the element type, that are defined on the domain of indexes valid for the collection and return the value of the element at that index.
PartialFunction.lift
is utility that lets you test whether a partial function is defined and apply it if it is in one go. If it is defined at the argument value, it will return the Option
of the result, otherwise, you will get None
.
So, test.lift(dim)
above returns None
if dim
was invalid, and Some
array otherwise. We then .fold
the option: .fold
returns first parameter is the option is empty, and executes the function if it is not.
Putting it all together: we get an Option
indicating whether the index was valid, then .fold
it to return 0 if it was empty or 1 if not.
Upvotes: 4
Reputation: 27971
You need an if-clause in your match-case if you need to test a boolean expression. Try this:
dim match {
case i if i < maxDim => 1
case _ => 0
}
Upvotes: 2