Command Line Flags in OCaml

Here’s the translation of the Go code to OCaml, along with explanations in Markdown format suitable for Hugo:

Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag.

OCaml provides an Arg module in its standard library for parsing command-line arguments. We’ll use this module to implement our example command-line program.

open Printf

let word = ref "foo"
let numb = ref 42
let fork = ref false
let svar = ref "bar"

let spec_list = [
  ("-word", Arg.Set_string word, "a string");
  ("-numb", Arg.Set_int numb, "an int");
  ("-fork", Arg.Set fork, "a bool");
  ("-svar", Arg.Set_string svar, "a string var");
]

let usage_msg = "Usage: command_line_flags [OPTIONS]"

let () =
  Arg.parse spec_list (fun x -> Printf.printf "Unrecognized argument: %s\n" x) usage_msg;
  printf "word: %s\n" !word;
  printf "numb: %d\n" !numb;
  printf "fork: %b\n" !fork;
  printf "svar: %s\n" !svar;
  printf "tail: %s\n" (String.concat " " (Array.to_list Sys.argv))

In this OCaml program:

  1. We define reference variables for each flag we want to parse. These are mutable and will be updated when the corresponding flags are provided.

  2. We create a spec_list that defines how each flag should be handled. Each entry in this list is a tuple containing the flag name, the action to take when the flag is encountered, and a description.

  3. We use Arg.parse to parse the command-line arguments based on our spec_list. Any unrecognized arguments will be printed with an error message.

  4. After parsing, we print out the values of all our flags, as well as any trailing arguments (which in this case will be the entire command line).

To experiment with this program, compile it and then run the resulting executable:

$ ocamlc command_line_flags.ml -o command_line_flags

Try out the compiled program by providing values for all flags:

$ ./command_line_flags -word opt -numb 7 -fork -svar flag
word: opt
numb: 7
fork: true
svar: flag
tail: ./command_line_flags -word opt -numb 7 -fork -svar flag

Note that if you omit flags, they automatically take their default values:

$ ./command_line_flags -word opt
word: opt
numb: 42
fork: false
svar: bar
tail: ./command_line_flags -word opt

The Arg module in OCaml automatically generates help text for the command-line program. You can view this by using the -help flag:

$ ./command_line_flags -help
Usage: command_line_flags [OPTIONS]
  -word a string
  -numb an int
  -fork a bool
  -svar a string var
  -help  Display this list of options
  --help  Display this list of options

If you provide a flag that wasn’t specified in the spec_list, the program will print an error message:

$ ./command_line_flags -wat
Unrecognized argument: -wat

This OCaml implementation provides similar functionality to the original program, allowing for command-line flag parsing with default values and help text generation.