Multiple Return Values in F#

F# has built-in support for multiple return values through tuples. This feature is used often in idiomatic F#, for example to return both result and error values from a function.

The int * int in this function signature shows that the function returns a tuple of 2 ints.

let vals () = (3, 7)

Here’s how we use the function and handle its return values:

let main() =
    // Here we use the 2 different return values from the
    // call with pattern matching.
    let (a, b) = vals()
    printfn "%d" a
    printfn "%d" b

    // If you only want a subset of the returned values,
    // use the wildcard pattern '_'.
    let (_, c) = vals()
    printfn "%d" c

main()

To run the program, you would typically save it as a .fs file and use the F# compiler or an F# interactive environment.

$ dotnet fsi multiple-return-values.fs
3
7
7

F# provides a concise and type-safe way to work with multiple return values through its tuple system and pattern matching capabilities. This allows for expressive and readable code when dealing with functions that need to return more than one value.

Accepting a variable number of arguments is another feature available in F#; we’ll look at this in a future example.