F # Tutorial File
//
This file contains sample code to guide you through the
Primitives of the F # language.
//
Learn more about F # at Http://fsharp.net
//
For a larger collection of the samples of F #, to:
http://go.microsoft.com/fwlink/?LinkID=124614
//
Contents:
-Simple computations
-Functions on integers
-Tuples
-Booleans
-Strings
-Lists
-Arrays
-More collections
-Functions
-Types:unions
-Types:records
-Types:classes
-Types:interfaces
-Types:classes with interface implementations
-Printing
Open some standard namespaces
Open System
Simple computations
// ---------------------------------------------------------------
Here are some simple computations. How to code can be documented
With '///' comments. Hover over any reference to a variable to
Documentation.
A very simple constant integer
Let Int1 = 1
A second very simple constant integer
Let Int2 = 2
ADD two integers
Let Int3 = Int1 + int2
functions on integers
// ---------------------------------------------------------------
A function on integers
Let f x = 2*x*x-5*x + 3
The result is a simple computation
Let result = f (Int3 + 4)
Another function on integers
Let increment x = x + 1
Compute the factorial of an integer
Let rec factorial n = if n=0 then 1 else n * Factorial (n-1)
Compute the highest-common-factor of two integers
Let rec hcf a b =//Notice:2 parameters separated by spaces
If A=0 then B
Elif A<b then hcf A (b-a)//notice:2 arguments-separated by spaces
else HCF (a-b) b
Note:function arguments are usually space separated
Note: ' Let rec ' defines a recursive function
Tuples
// ---------------------------------------------------------------
A simple tuple of integers
Let Pointa = (1, 2, 3)
A simple tuple of an integer, a string and a double-precision floating point number
Let Datab = (1, "Fred", 3.1415)
A function that swaps the order of two values in a tuple
Let Swap (A, b) = (b, a)
Booleans
// ---------------------------------------------------------------
A Simple Boolean value
Let Boolean1 = True
A Second Simple Boolean value
Let boolean2 = False
Compute a new Boolean using ANDs, ors, and Nots
Let boolean3 = Not boolean1 && (boolean2 | | false)
Strings
// ---------------------------------------------------------------
A Simple string
Let Stringa = "Hello"
A Second Simple string
Let STRINGB = "the World"
"Hello World" computed using string concatentation
Let STRINGC = Stringa + "" + STRINGB
"Hello World" computed using a. NET library function
Let Stringd = String.Join ("", [| Stringa; STRINGB |])
Try re-typing the above line to the = IntelliSense in action
Note, ctrl-j on (partial) identifiers re-activates it
Functional Lists
// ---------------------------------------------------------------
The empty list
Let Lista = []
A list with 3 integers
Let Listb = [1; 2; 3]
A list with 3 integers, note:: Is the ' cons ' Operation
Let LISTC = 1:: [2; 3]
Compute the sum of a list of integers using a recursive function
Let rec sumlist xs =
Match XS with
| []-> 0
| Y::ys-> y + sumlist ys
Sum of a list
Let listd = sumlist [1; 2; 3]
The list of integers between 1 inclusive
Let Onetoten = [1..10]
The squares of the the integers
Let Squaresofonetoten = [for x in 0..10-> x*x]
Mutable Arrays
// ---------------------------------------------------------------
Create an array
Let arr = array.create 4 "Hello"
ARR.[1] <-"World"
ARR.[3] <-"Don"
Compute the length of the array by using a instance method on the Array object
Let Arrlength = arr. Length
Extract a sub-array using slicing notation
Let front = arr.[0..2]
More collections
// ---------------------------------------------------------------
A dictionary with integer keys and string values
Let lookuptable = Dict [(1, "one"); (2, "two")]
Let onestring = lookuptable. [1]
For some other common data structures:
System.Collections.Generic
Microsoft.FSharp.Collections
Microsoft.FSharp.Collections.Seq
Microsoft.FSharp.Collections.Set
Microsoft.FSharp.Collections.Map
Functions
// ---------------------------------------------------------------
A function that squares its input
Let Square x = x*x
Map a function across a list of values
Let squares1 = List.map Square [1; 2; 3; 4]
Let Squares2 = List.map (fun x-> x*x) [1; 2; 3; 4]
Pipelines
Let squares3 = [1; 2 3; 4] |> List.map (fun x-> x*x)
Let Sumofsquaresupto n =
[1..N]
|> List.map Square
|> List.sum
Types:unions
// ---------------------------------------------------------------
Type Expr =
| Num of INT
| Add of expr * expr
| Mul of expr * expr
| Var of String
Let rec Evaluate (env:map<string,int>) exp =
Match exp with
| Num N-> N
| ADD (x,y)-> Evaluate env x + Evaluate env y
| Mul (x,y)-> Evaluate env x * Evaluate env y
| Var ID-> env. [ID]
Let Enva = map.of_list ["a", 1;
"B", 2;
"C", 3]
Let expT1 = Add (Var "A", Mul (Num 2,var "B"))
Let resT1 = Evaluate Enva expT1
Types:records
// ---------------------------------------------------------------
Type card = {name:string;
phone:string;
Ok:bool}
Let Carda = {Name = "Alf"; Phone = "(206) 555-8257"; Ok = False}
Let Cardb = {Carda with Phone = "(206) 555-4112"; Ok = true}
Let Showcard C =
C.name + "Phone:" + C.phone + (if not C.ok then "(unchecked)" Else ")
Types:classes
// ---------------------------------------------------------------
A 2-dimensional Vector
Type vector2d (dx:float, dy:float) =
The pre-computed length of the vector
Let length = sqrt (dx*dx + dy*dy)
The displacement along the x-axis
member V.DX = DX
The displacement along the y-axis
member V.dy = DY
The length of the vector
member V.length = Length
Re-scale the vector by a constant
Member V.scale (k) = Vector2d (K*DX, K*dy)
Types:interfaces
// ---------------------------------------------------------------
Type Ipeekpoke =
Abstract Peek:unit-> int
Abstract Poke:int-> Unit
Types:classes with interface implementations
// ---------------------------------------------------------------
A widget which counts the number of times it is poked
Type Widget (initialstate:int) =
The internal state of the Widget
Let mutable state = Initialstate
Implement the Ipeekpoke interface
Interface Ipeekpoke with
Member X.poke (n) = State <-state + N
Member X.peek () = State
Has the Widget been poked?
member x.hasbeenpoked = (State <> 0)
Let widget = Widget (:> ipeekpoke)
Widgets. Poke (4)
Let Peekresult = widget. Peek ()
Printing
// ---------------------------------------------------------------
Print an integer
PRINTFN "Peekresult =%d" Peekresult
Print a result using%A for generic printing
Printfn "LISTC =%A" LISTC