Saturday, July 18, 2009

F# Syntax

What does a developer gain by learning features from different styles of programming? Read this announcement from Microsoft's .Net website to see how the .Net platform is growing and contemplate what motivated the development of this new feature:

The upcoming 4.0 release of Microsoft .NET Framework introduces a new type called System.Tuple. System.Tuple is a fixed-size collection of heterogeneously typed data. Like an array, a tuple has a fixed size that can't be changed once it has been created. Unlike an array, each element in a tuple may be a different type, and a tuple is able to guarantee strong typing for each element.

F# included its own implementation of the Tuple and Microsoft have decided to extend this data structure to the base API of the .Net platform. There is nothing new in the world that suddenly required a Tuple where none was needed before. The Tuple is, as many other things proclaim themselves to be these days, the answer to Moore's Law falling off a cliff. The need for a heterogeneous datastructure has been with us since the dawn of the computing age. It was implemented as the Record in Pascal, the Struct in C and the class in Java and C#.

Enough editorializing. The language features of F# include ...

List Construction
[greg:mono] cd FSharp-1.9.6.16
[greg:FSharp-1.9.6.16] mono bin/fsi.exe
> [];;
val it : 'a list = []
> [1;2];;
val it : int list = [1; 2]
> 1 :: [2;3];;
val it : int list = [1; 2; 3]
> [1;2] @ [3;4];;
val it : int list = [1; 2; 3; 4]
> [1;2;3] @ [4 .. 9];;
val it : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9]
List Head and Tail
> let ml = [1;2;3];;

val ml : int list = [1; 2; 3]

> List.hd ml;;
val it : int = 1

> List.tl ml;;
val it : int list = [2; 3]
Assignment
> let evenNumbers = [2;4;6;8;10];;

val evenNumbers : int list = [2; 4; 6; 8; 10]

> let languages = ["Ruby";"F#";"Java"];;

val languages : string list = ["Ruby"; "F#"; "Java"]
Arrays
> (1,2,3);;

val it : int * int * int = (1, 2, 3)

> let nbrs=("one","two","three");;

val nbrs : string * string * string = ("one", "two", "three")
Range and Sequence
let range = seq{0 .. 2 .. 8};;

val range : seq

> for i in range do
   printfn "i = %d" i;;
i = 0
i = 2
i = 4
i = 6
i = 8
val it : unit = ()