Math OperatorsPerform computations on numbers with math operators. Call pown, abs, floor and ceil.
This page was last reviewed on Mar 1, 2023.
Math. In F# a certain value is -10, but is changed to 10. An absolute value is always positive. We can compute this with some logic. But abs is built-in—it is easier to call.
With special operators, we call built-in mathematical methods. For example, with "pown" we compute an exponent of an integer. This makes programs clearer to read.
Exponents. Let us begin with some exponentiation. Please note that we can call methods from System.Math also, but F# provides some shortcuts.
Detail We first use pown to take the power of a number (an int). We square the value 4 to get 16.
Detail We use two starts to apply a power to a double. We must use 2.0 instead of 2 to square here.
// Use pown to implement integer exponents. let number = 4 let squared = pown number 2 printfn "%A" squared // Use two stars to implement double-type exponents. let numberDouble = 4.0 let squaredDouble = numberDouble ** 2.0 printfn "%A" squaredDouble
16 16.0
Abs. The absolute value of a number is positive. Numbers that are already positive are not changed. Abs is useful when computing indexes (like with hash codes).
// The absolute value of -10 is 10. let result1 = abs -10 printfn "%A" result1 // For positive numbers, nothing is changed. let result2 = abs 1 printfn "%A" result2
10 1
Floor, ceil. We have operators that access many common math methods. For example floor and ceil access the Math.Floor and Math.Ceiling methods.
// Take the floor of a number with the operator. let result1 = floor 2.9 printfn "%A" result1 // Take ceiling of a number. let result2 = ceil 1.1 printfn "%A" result2
2.0 2.0
Max, min. We pass two Int arguments to these functions. They return the bigger (for max) or the smaller number (for min). These are built into the F# language.
let numberSmaller = 10 let numberBigger = 20 // Get the max of the two numbers. let bigger = max numberSmaller numberBigger printfn "%A" bigger // Get the min. let smaller = min numberSmaller numberBigger printfn "%A" smaller
20 10
Odd, even. A number can be odd or even—this is the parity of the number. In F# we use Seq.where to filter based on the parity of numbers. We even generate odd and even sequences.
Odd, Even
A summary. F# programs often extensively use numbers. We find these mathematical operators make programs easier to understand to write. When compatible, they should be preferred.
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.
© 2007-2023 Sam Allen.