Saturday, November 12, 2011

F# Primitive Types


A type is 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 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 – squre 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 explicity 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.Numerics
let megabyte = 1024I * 1024I
let gigabyte = megabyte * 1024I

Although BigInt is heavily optimized for performance, itz much slower than using the primitive integer data types.

No comments:

Post a Comment