Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern match for Integer range

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?

like image 475
dublintech Avatar asked Jan 13 '13 20:01

dublintech


People also ask

How do I match a range of numbers in regex?

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).

How does regex match 4 digits?

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.

How do I match a pattern in regex?

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).

Why * is used in regex?

- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"


3 Answers

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;
} 
like image 116
om-nom-nom Avatar answered Nov 01 '22 01:11

om-nom-nom


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.

like image 21
David M Avatar answered Nov 01 '22 00:11

David M


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
}
like image 30
pestilence669 Avatar answered Nov 01 '22 00:11

pestilence669