Use modulo division to test for even and odd numbers. Call filter to generate sequences of even and odd values.Odd, even. 1 is odd. 2 is even. We all know this, but how do we compute this? With Scala we use modulo division to see if 2 divides a number evenly (with no remainder).With def, we define two small functions that return Booleans. With isEven we return true if a number is evenly divisible by 2. And with isOdd we do the opposite.Example methods. Let us begin. With isEven we use a short syntax form in Scala to return whether the modulo division of a number by 2 equals 0. With isOdd we simply return “not isEven.”
List.range: We invoke this method to get a short list of numbers to test. We test each Int for even and odd status.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | object Main { // These functions test for even and odd numbers. def isEven(number: Int) = number % 2 == 0 def isOdd(number: Int) = !isEven(number) def main(args: Array[String]): Unit = { // Generate a range of numbers to test. val tests = List.range(-2, 10) // Loop over numbers and indicate whether they are even or odd. for (n <- tests) { print(n) if (isEven(n)) { println(" -> Even") } if (isOdd(n)) { println(" -> Odd") } } } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | -2 -> Even -1 -> Odd 0 -> Even 1 -> Odd 2 -> Even 3 -> Odd 4 -> Even 5 -> Odd 6 -> Even 7 -> Odd 8 -> Even 9 -> Odd |
Filter, generate sequences. Let us add some complexity. We repeat our isEven and isOdd numbers. We use Seq.range and then filter() to generate sequences of even and odd numbers.
FilterNot: We use filterNot with isEven to generate odd numbers—this is another way of generating odds.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | object Main { // Tests parity of numbers. def isEven(number: Int) = number % 2 == 0 def isOdd(number: Int) = !isEven(number) def main(args: Array[String]): Unit = { // Generate even numbers. println("Filter even") val evens = Seq.range(0, 10).filter(isEven(_)) println(evens) // Generate odd numbers. println("Filter odd") val odds = Seq.range(0, 10).filter(isOdd(_)) println(odds) // Another way to get odd numbers. println("Filter not even") val odds2 = Seq.range(0, 10).filterNot(isEven(_)) println(odds2) } } |
Output:
1 2 3 4 5 6 7 8 | Filter even Vector(0, 2, 4, 6, 8) Filter odd Vector(1, 3, 5, 7, 9) Filter not even Vector(1, 3, 5, 7, 9) |