Command Line Arguments in OCaml

Command-line arguments are a common way to parameterize execution of programs. For example, ocamlc -o hello hello.ml uses -o, hello, and hello.ml as arguments to the ocamlc program.

(* Command-line arguments can be accessed using the Sys.argv array *)
let () =
  (* Sys.argv provides access to raw command-line arguments.
     Note that the first value in this array is the path to the program,
     and Sys.argv.(1) onwards holds the arguments to the program. *)
  let args_with_prog = Array.to_list Sys.argv in
  let args_without_prog = List.tl args_with_prog in

  (* You can get individual args with normal indexing *)
  let arg = Sys.argv.(3) in

  Printf.printf "%s\n" (String.concat " " args_with_prog);
  Printf.printf "%s\n" (String.concat " " args_without_prog);
  Printf.printf "%s\n" arg

To experiment with command-line arguments, it’s best to compile the program first:

$ ocamlc -o command_line_arguments command_line_arguments.ml
$ ./command_line_arguments a b c d
./command_line_arguments a b c d
a b c d
c

In OCaml, we use the Sys.argv array to access command-line arguments. The first element (Sys.argv.(0)) is the program name, and subsequent elements are the arguments passed to the program.

We convert the array to a list for easier manipulation. The List.tl function is used to get all elements except the first one (the program name).

Individual arguments can be accessed using array indexing, as shown with Sys.argv.(3).

The Printf.printf function is used to print the results, with String.concat joining the list elements into a single string.

Next, we’ll look at more advanced command-line processing with command-line parsing libraries in OCaml.