A type is an abstraction and is primarily about enforcing safety. F# is statically typed, meaning that type checking is done at compile time. For example, if a function accepts an integer as a parameter, you will get a compilation error if you try to pass a non integer value.
F# contains two varieties of numeric primitives as integer and floating point numbers. All numerical primitives are listed in the attached diagram. F# uses a let
binding to create a value for numeric primitives. It allows to specify values in hexadecimal (base 16), octal (base 8) or binary (base 2) with prefix 0x, 0o, 0b. Few let
bindings are:
> let hex =0xFCAF;;val hex : int = 64687> let bin =0b00101010y;;val bin : sbyte = 43y
Arithmetic
You can use standard arithmetic operators on numeric primitives as +, -, *, /. Sample F# code is:
> 32450s + 1s;;val it : int16 = 32451s
By default, arithmetic operators do not check for overflow. So, if you exceed the range, the result will overflow to be negative.
Math
F# features all the standard math functions as:
abs
- Absolute value of a number ceil
– Round up to the nearest number exp
– Raise a value to a power of e
floor
– Round down to the nearest integer pown
– Power of an integer sqrs
– Square root of a given number
Conversion
F# doesn’t perform implicit conversions for primitive types. As an example, assigning int64
to int16
eliminates subtle bugs by removing surprise conversions. Developer must use an explicit conversion function like System.Convert
.
Bitwise Operation
Primitive integer types support bitwise operators for manipulating values at a binary level. Bitwise operators are &&& - and, ||| - or, ^^^ - xor, <<< - left shift, >>> - right shift.
BigInt
If the application is dealing with larger data, F# provides BigInt
type for representing arbitrarily long integers. BigInt
uses I suffix for literals as:
> open System.Numericslet megabyte = 1024I * 1024Ilet gigabyte = megabyte * 1024I
Although BigInt
is heavily optimized for performance, it's much slower than using the primitive integer data types.