- F# - Namespaces
- F# - Modules
- F# - Events
- F# - Interfaces
- F# - Inheritance
- F# - Operator Overloading
- F# - Structures
- F# - Classes
- F# - Exception Handling
- F# - Pattern Matching
- F# - Enumerations
- F# - Delegates
- F# - Generics
- F# - Basic I/O
- F# - Mutable Dictionary
- F# - Mutable Lists
- F# - Arrays
- F# - Mutable Data
- F# - Discriminated Unions
- F# - Maps
- F# - Sets
- F# - Sequences
- F# - Lists
- F# - Records
- F# - Tuples
- F# - Options
- F# - Strings
- F# - Functions
- F# - Loops
- F# - Decision Making
- F# - Operators
- F# - Variables
- F# - Data Types
- F# - Basic Syntax
- F# - Program Structure
- F# - Environment Setup
- F# - Overview
- F# - Home
F# Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
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 Ap”, “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 Inspanidual Tuple Members
The inspanidual 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 Ap", "Hyderabad", 10 )
When you compile and execute the program, it yields the following output −
Detail Info: "Zara Ap" "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", "Ap") 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: "Ap"Advertisements