Home
Map
Odd and Even NumbersUse modulo division to test for even and odd numbers. Call filter to generate sequences of even and odd values.
Scala
Odd, even. 1 is odd and 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."
Detail We invoke this method to get a short list of numbers to test. We test each Int for even and odd status.
// These functions test for even and odd numbers. def isEven(number: Int) = number % 2 == 0 def isOdd(number: Int) = !isEven(number) // 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") } }
-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.
Detail We use filterNot with isEven to generate odd numbers—this is another way of generating odds.
// Tests parity of numbers. def isEven(number: Int) = number % 2 == 0 def isOdd(number: Int) = !isEven(number) // 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)
Filter even List(0, 2, 4, 6, 8) Filter odd List(1, 3, 5, 7, 9) Filter not even List(1, 3, 5, 7, 9)
A review. Testing a number's parity is simple. And with methods like filter and filterNot we can generate ranges of numbers based on their parity.
C#VB.NETPythonGoJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.