We have some numbers: 10, 11, 12. These are even, odd and even. We can test the parity of a number (whether it is odd or even) with simple functions.
With Seq
and sequence expressions, we can get sequences of numbers that are only odd or even. Advanced F# features can be helpful here.
This first example introduces two functions, isEven
and isOdd
. With isEven
we return true if the argument is evenly divisible by 2.
isOdd
, we simply return true when isEven
is false (odd is the logical opposite of even).isOdd
and isEven
).// 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" evensseq [1; 3; 5; 7; ...] seq [0; 2; 4; 6; ...]
Sometimes we do not want to filter an existing sequence. We can just generate a new sequence in F# with sequence expressions.
for
-loop. We can use "seq
" or square brackets—they both generate sequences.printfn
over all elements in the resulting 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 Odd: -5 Odd: -3 Odd: -1 Odd: 1 Odd: 3 Odd: 5 Even: -4 Even: -2 Even: 0 Even: 2 Even: 4
With isOdd
and isEven
, we can invoke many of the Seq
methods. For example, we can use Seq.where()
to filter out all other numbers.
In numeric programs, the parity of numbers is sometimes important. And testing for odd and even numbers can help with puzzle solving. An odd number is (simply) not even.