Variadic Functions in F#

Here’s a function that will take an arbitrary number of ints as arguments.

open System

let sum (nums: int seq) =
    printf "%A " nums
    let total = Seq.sum nums
    printfn "%d" total

let main () =
    // Variadic functions can be called in the usual way with individual arguments.
    sum [1; 2]
    sum [1; 2; 3]

    // If you already have multiple args in a list, apply them to a variadic function using
    // Seq.toList to convert them to a list like this.
    let nums = [1; 2; 3; 4]
    sum nums

// Entry point of the program
main ()

To run this F# code, place it in a file named variadic-functions.fsx and use dotnet fsi to execute it.

$ dotnet fsi variadic-functions.fsx

Output:

[1; 2] 3
[1; 2; 3] 6
[1; 2; 3; 4] 10

Another key aspect of functions is their ability to form closures, which we’ll look at next.