Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a specific member in a F# tuple

Tags:

tuples

f#

In F# code I have a tuple:

let myWife=("Tijana",32) 

I want to access each member of the tuple separately. For instance this what I want to achieve by I can't

Console.WriteLine("My wife is {0} and her age is {1}",myWife[0],myWife[1]) 

This code doesn't obviously work, by I think you can gather what I want to achieve.

like image 942
Nikola Stjelja Avatar asked Mar 01 '09 18:03

Nikola Stjelja


2 Answers

You want to prevent your wife from aging by making her age immutable? :)

For a tuple that contains only two members, you can fst and snd to extract the members of the pair.

let wifeName = fst myWife; let wifeAge = snd myWife; 

For longer tuples, you'll have to unpack the tuple into other variables. For instance,

let _, age = myWife;; let name, age = myWife;; 
like image 121
Curt Hagenlocher Avatar answered Sep 22 '22 19:09

Curt Hagenlocher


Another quite useful thing is that pattern matching (just like when extracting elements using "let" binding) can be used in other situations, for example when writing a function:

let writePerson1 person =   let name, age = person   printfn "name = %s, age = %d" name age  // instead of deconstructing the tuple using 'let',  // we can do it in the declaration of parameters let writePerson2 (name, age) =    printfn "name = %s, age = %d" name age  // in both cases, the call is the same writePerson1 ("Joe", 20) writePerson2 ("Joe", 20) 
like image 30
Tomas Petricek Avatar answered Sep 22 '22 19:09

Tomas Petricek