C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
List.range: We invoke this method to get a short list of numbers to test. We test each Int for even and odd status.
Scala program that test seven, odd numbers
// 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")
}
}
Output
-2 -> Even
-1 -> Odd
0 -> Even
1 -> Odd
2 -> Even
3 -> Odd
4 -> Even
5 -> Odd
6 -> Even
7 -> Odd
8 -> Even
9 -> Odd
FilterNot: We use filterNot with isEven to generate odd numbers—this is another way of generating odds.
Scala program that uses filter on even, odd numbers
// 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)
Output
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)