Variadic Functions in OCaml

Based on the code example provided, here is the Go code example translated to OCaml and the corresponding explanation:

Variadic functions can be called with any number of trailing arguments. Here is a function that will take an arbitrary number of integers as arguments.

let sum nums =
  List.iter (Printf.printf "%d ") nums;
  let total = List.fold_left (+) 0 nums in
  Printf.printf "%d\n" total

let () = 
  sum [1; 2];
  sum [1; 2; 3];
  let nums = [1; 2; 3; 4] in
  sum nums

In this OCaml code:

  • We define a function sum that takes a list of integers nums.
  • We use List.iter along with Printf.printf to print each number in the list followed by a space.
  • We calculate the total sum of the integers using List.fold_left and print the total sum.
  • In the main part of the code, we call the sum function with different numbers of arguments.

To run the program, save the code in a file, e.g., variadic_functions.ml, and use the OCaml compiler to execute it.

$ ocamlc -o variadic_functions variadic_functions.ml
$ ./variadic_functions
1 2 3
1 2 3 6
1 2 3 4 10

Now that we can run and build basic OCaml programs, let’s learn more about the language.