50

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.

1
  • 7
    It doesn't work because the PC is scared of spitting out your wife age.
    – Kafo
    Mar 24, 2017 at 18:48

4 Answers 4

91

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;;
0
24

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)
0
17

You can use the function fst to get the first element, and snd to get the second ekement. You can also write your own 'third' function:

let third (_, _, c) = c

Read more here: F# Language reference, Tuples

1
  • 4
    +1 but surely trd or tri would represent more idiomatic naming :) Dec 1, 2013 at 2:17
9

You can also write an unpack function for a certain length:

let unpack4 tup4 ind =
    match ind, tup4 with
    | 0, (a,_,_,_) -> a
    | 1, (_,b,_,_) -> b
    | 2, (_,_,c,_) -> c
    | 3, (_,_,_,d) -> d
    | _, _ -> failwith (sprintf "Trying to access item %i of tuple with 4 entries." ind) 

or

let unpack4 tup4 ind =
    let (a, b, c, d) = tup4
    match ind with
    | 0 -> a
    | 1 -> b
    | 2 -> c
    | 3 -> d
    | _ -> failwith (sprintf "Trying to access item %i of tuple with 4 entries." ind) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.