5

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?

dublintech
  • 16,815
  • 29
  • 84
  • 115
  • om-nom-nom has the answer. To my knowledge, _no_ common modern programming language allows the kind of shorthand notation you used. Note, too, that you don't need the outer-most parentheses surrounding the guard expression and semicolons in Scala are very bad style! Also, only put a space to the left of a colon when you're using the context bound syntax. – Randall Schulz Jan 13 '13 at 21:25
  • @RandallSchulz python can do this. Actually I've seen that somebody on scala mailing list done this with scala as well, but with some additional trickery. Cant find it now. – om-nom-nom Jan 13 '13 at 21:46
  • Duplicate of http://stackoverflow.com/questions/1346127/can-a-range-be-matched-in-scala. – Glenn Feb 12 '15 at 15:15

3 Answers3

20

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;
} 
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
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.

David M
  • 71,481
  • 13
  • 158
  • 186
4

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
}
pestilence669
  • 5,698
  • 1
  • 23
  • 35