C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: With isOdd, we simply return true when isEven is false (odd is the logical opposite of even).
Seq.where: We filter our sequence based on whether numbers are odd or even (based on the results of isOdd and isEven).
SeqF# program that tests for even, odd numbers
// Even numbers are divisible by 2.
let isEven x = (x % 2) = 0
// Odd numbers are not even.
let isOdd x = isEven x = false
// Generate numbers 0 through 10.
let result = [0 .. 10]
// Get odd numbers and even numbers.
let odds = Seq.where (fun x -> isOdd x) result
let evens = Seq.where (fun x -> isEven x) result
// Print our results.
printfn "%A" odds
printfn "%A" evens
Output
seq [1; 3; 5; 7; ...]
seq [0; 2; 4; 6; ...]
Here: We use the yield keyword in a for-loop. We can use "seq" or square brackets—they both generate sequences.
Seq.iter: We use this function to invoke printfn over all elements in the resulting sequences.
PrintfnF# program that generates odd, even sequences
// Generate sequence of odd numbers.
let odds = seq { for i in -5 .. 5 do
if not (i % 2 = 0) then
yield i }
// Generate sequence of even numbers.
// ... Use slightly different syntax form.
let evens = [for i in -5 .. 5 do
if (i % 2 = 0) then
yield i]
// Print all odd numbers.
Seq.iter (fun x -> printfn " Odd: %A" x) odds
// Print all even numbers.
Seq.iter (fun x -> printfn "Even: %A" x) evens
Output
Odd: -5
Odd: -3
Odd: -1
Odd: 1
Odd: 3
Odd: 5
Even: -4
Even: -2
Even: 0
Even: 2
Even: 4