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.
Let us begin with some exponentiation. Please note that we can call methods from System.Math
also, but F# provides some shortcuts.
int
). We square the value 4 to get 16.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" squaredDouble16 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" result210 1
Floor
, ceilWe 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" result22.0 2.0
Max
, minWe 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" smaller20 10
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.
F# programs often extensively use numbers. We find these mathematical operators make programs easier to understand to write. When compatible, they should be preferred.