F# Tutorial on F# Tuples

a tuple is a comma-separated collection of values. these are used for creating ad hoc data structures, which group together related values.

for example, (“zara ali”, “hyderabad”, 10) is a 3-tuple with two string values and an int value, it has the type (string * string * int).

tuples could be pairs, triples, and so on, of the same or different types.

some examples are provided here −

// tuple of two integers.
( 4, 5 )

// triple of strings.
( "one", "two", "three" )

// tuple of unknown types.
( a, b )

// tuple that has mixed types.
( "absolute classes", 1, 2.0 )

// tuple of integer expressions.
( a * 4, b + 7)

example

this program has a function that takes a tuple of four float values and returns the average −

let averagefour (a, b, c, d) =
   let sum = a + b + c + d
   sum / 4.0

let avg:float = averagefour (4.0, 5.1, 8.0, 12.0)
printfn "avg of four numbers: %f" avg

when you compile and execute the program, it yields the following output −

avg of four numbers: 7.275000

accessing individual tuple members

the individual members of a tuple could be assessed and printed using pattern matching.

the following example illustrates the concept −

example

let display tuple1 =
   match tuple1 with
   | (a, b, c) -> printfn "detail info: %a %a %a" a b c

display ("zara ali", "hyderabad", 10 )

when you compile and execute the program, it yields the following output −

detail info: "zara ali" "hyderabad" 10

f# has two built-in functions, fst and snd, which return the first and second items in a 2-tuple.

the following example illustrates the concept −

example

printfn "first member: %a" (fst(23, 30))
printfn "second member: %a" (snd(23, 30))

printfn "first member: %a" (fst("hello", "world!"))
printfn "second member: %a" (snd("hello", "world!"))

let nametuple = ("zara", "ali")

printfn "first name: %a" (fst nametuple)
printfn "second name: %a" (snd nametuple)

when you compile and execute the program, it yields the following output −

first member: 23
second member: 30
first member: "hello"
second member: "world!"
first name: "zara"
second name: "ali"