Variadic Functions in Standard ML

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function.

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

fun sum(nums: int list): unit = 
    let
        fun printList [] = ()
          | printList (x::xs) =
            (print (Int.toString x ^ " "); printList xs)

        fun totalSum [] acc = acc
          | totalSum (x::xs) acc = totalSum xs (acc + x)

        val _ = printList nums
        val total = totalSum nums 0
    in
        print (Int.toString total ^ "\n")
    end

Within the function, nums is a list of integers. We can use list-processing functions: print each element and calculate the sum.

fun main (): unit =
    let
        val _ = sum [1, 2]
        val _ = sum [1, 2, 3]
        val _ = sum [1, 2, 3, 4]
    in
        ()
    end

Variadic functions can be called in the usual way with individual arguments.

val nums = [1, 2, 3, 4]
val _ = sum nums

If you already have multiple args in a list, you can pass them directly as in this example.

$ sml variadic-functions.sml
[1 2] 3
[1 2 3] 6
[1 2 3 4] 10