O'Reilly logo

Real World OCaml by Jason Hickey, Anil Madhavapeddy, Yaron Minsky

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 14. Command-Line Parsing

Many of the OCaml programs that you’ll write will end up as binaries that need to be run from a command prompt. Any nontrivial command line should support a collection of basic features:

  • Parsing of command-line arguments

  • Generation of error messages in response to incorrect inputs

  • Help for all the available options

  • Interactive autocompletion

It’s tedious and error-prone to code all of this manually for every program you write. Core provides the Command library, which simplifies all of this by letting you declare all your command-line options in one place and by deriving all of the above functionality from these declarations.

Command is simple to use for simple applications but also scales well as your needs grow more complex. In particular, Command provides a sophisticated subcommand mode that groups related commands together as the complexity of your user interface grows. You may already be familiar with this command-line style from the Git or Mercurial version control systems.

In this chapter, we’ll:

  • Learn how to use Command to construct basic and grouped command-line interfaces

  • We will build simple equivalents to the cryptographic md5 and shasum utilities

  • Demonstrate how functional combinators can be used to declare complex command-line interfaces in a type-safe and elegant way

Basic Command-Line Parsing

Let’s start by working through a clone of the md5sum command that is present on most Linux installations (the equivalent command on Mac OS X is simply

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required