Odd, Even NumbersCheck for even and odd numbers with modulo division. The Seq.where function with lambdas checks sequences for parity.
F#
Odd, even. 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.
Test for odd, even. This first example introduces two functions, isEven and isOdd. With isEven we return true if the argument is evenly divisible by 2.
fun
And With isOdd, we simply return true when isEven is false (odd is the logical opposite of even).
Detail We filter our sequence based on whether numbers are odd or even (based on the results of isOdd and isEven).
Seq
// 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
seq [1; 3; 5; 7; ...] seq [0; 2; 4; 6; ...]
Generate odd, evens. Sometimes we do not want to filter an existing sequence. We can just generate a new sequence in F# with sequence expressions.
Here We use the yield keyword in a for-loop. We can use "seq" or square brackets—they both generate sequences.
Detail We use this function to invoke printfn over all elements in the resulting sequences.
printfn
// 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.
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.