Sunday, August 2, 2009

Tuples and Record

When I sit down to learn a language and I learn it has tuples I immediately smile. They are an nice feature to any language and F# has a nice implementation of them.

Like every other data structure they are quite easy to implement
let aTuple = (1, 2);;

Another nice feature is that tuples also work with the F# pattern matching, an example is as follows.

let greeting (name, language) =    
 match (name, language) with     
| ("Steve", _) -> "Howdy, Steve"    
| (name, "English") -> "Hello, " + name     
| (name, _) when language.StartsWith("Span") -> "Hola, " + name     
| (_, "French") -> "Bonjour!"     
| _ -> "DOES NOT COMPUTE"


So the '_' operator, which is the match everything also works in tuples. So again super fun happy time.

So then we move onto Records. In my head the main difference between a tuple is and a record is persistence.  A tuple to me feels like a throw away value where as a record, since the fields are name has aa degree of persistence. 

Compare to most other F#, Records have a slightly different syntax. 
First you need to define you record. 

type website = 
 { title: string;
    url: string};;

then you define it like normal

let google = {url = "http://www.google.com"; title = "google"};;

As you can see, the order of the attributes do not matter. 

Now if you want to reference a Record you simply use the field name

Google.url;;


So easy.

Now here is the only hard bit to wrap your head around. F# is immutable, variables do not vary, hence why i call them values. Immutablity is a hard concept if you are new to it. At the heart of it the value will not change, instead you create a new one. 

So you delcare a Record, for example lets say a coordinate, 

type coordinate = 
 {X: float;
 Y : float};;

let start = { X = 1.0; Y = 1.0};;

So that delcares the starting point. But coordinates by there very nature change, if I cannot mutate the variable what do I do? well F#'s answer to this is to clone the value. 

let SetX item newX = 
 { item with X = newX};;

let finish = SetX start 15.0;;


That is F# Tuples and Records in a nutshell. 

No comments:

Post a Comment