FSharp

From ScienceZero
Revision as of 06:34, 23 August 2013 by Bjoern (Talk | contribs) (Values and Variables)

Jump to: navigation, search

Values and Variables

let a = 2
This is a value and it is constant within the scope of the value.
You can safely pass values to other threads, computers or to the other side of the world.
Always use values instead of variables when possible.
let mutable b = 2
This is a variable and it can be updated with a new value like in other laguanges
like this b <- b + 1

Functions

Everything is a function and returns a value.

let max = if a > b then a else b

If it makes no sense for a function to return a value it should return a value of type unit.

let a = ()

If the value returned from a function is not required it can be deleted by using the ignore function.

ignore (1 + 2)


Loops

Try to avoid loops when it is simple to do so because most loops require change of state to terminate and change of state is an opportunity for bugs.

while(true) do
    printfn "Hello World"
for i = 1 to 10 do
    printfn "%A" i
// This type of loop is quite safe
let arr = ["One";"Two";"Three"]
for t in arr do
    printfn "%A" t