The purpose of my function is to add 5 to an integer as long as that integer is greater than 0 and less than or equal to 7. I try:
val add5Partial : PartialFunction[Int, Int] = {
case d if (0 < d <= 7) => d + 5;
}
I get:
<console>:8: error: type mismatch;
found : Int(7)
required: Boolean
case d if (0 < d <= 7) => d + 5;
Any tips?
With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).
Add the $ anchor. /^SW\d{4}$/ . It's because of the \w+ where \w+ match one or more alphanumeric characters. \w+ matches digits as well.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"
Scala do not support such syntax out of the box, so you have to write:
val partial : Int => Int = {
case d if (d > 0) && (d <= 7) => d + 5;
}
Alternatively you could do:
val partial : Int => Int = {
case d if 1 to 7 contains d => d + 5;
}
You can't do this in a single comparison. You need to use:
(d > 0) && (d <= 7)
As you have done it, it will evaluate one comparison to a Boolean and then fail to use this as an int in the second comparison.
You can do any of the following:
val f = (n: Int) ⇒ if (n > 0 && n <= 7) n + 5 else n
// or ...
def f(n: Int) = if (n > 0 && n <= 7) n + 5 else n
// or ...
def f(n: Int): Int = n match {
case n if n > 0 && n <= 7 ⇒ n + 5
case _ ⇒ n
}
// or (to speak of ... the comment by @om-nom-nom)
def f(n: Int) = n match {
case n if 0 to 7 contains n ⇒ n + 5
case _ ⇒ n
}
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