Monday, February 2, 2009

F# – Typed tuples

F# is a typed language. I create 2 tuples containing site URLs and relevancies. I create a tuple from the tuples above. I execute a pattern matching on site1 tuple, splitting it up to a string and an integer variables. Finally I print the content of the url and relevance variable to the console.

let site1 = ("",10)
let site2 = ("",9)
let sites = (site1, site2)
let url,relevance = site1

printfn "site: %s" url
printfn "relevance: %d" relevance
relevance: 10

Let’s test type safety:

let url = url +2

> let url = url + 2;;

  let url = url + 2;;

stdin(34,17): error FS0001: The type 'int' does not match the type 'string'.

This error message means that integer cannot be converted to string.

Tuples can be used effectively in functions:

let increase (a,b) =

let printIncreased (a,b) =
    let (a,b) = increase (a,b)
    printfn "a: %d" a
    printfn "b: %d" b
printIncreased (5,6)
a: 6
b: 7

Finally a tuple with 4 elements:

let quad = ("Doe", "John", 23, "New York")
let last,first,age,location = quad
System.Console.WriteLine("Last name: {0}\nFirst name: {1}\nAge: {2}\nLocation: {3}", last, first, age, location)
Last name: Doe
First name: John
Age: 23
Location: New York