Pearls of OCaml Batteries (1)

OCaml Batteries logo

OCaml is known to be a powerful functional programming language, but one of its presumed weakness is a relatively poor standard library.

By accident, I'm one of the few people on the planet considering this very clean and virtually bug free library a feature and not a bug, but this is only an opinion.

The standard library contains everything you need to build applications and other libraries, but it's essential, forget something like the Python standard library and things like “sending an email in one line of code”. Instead, think of the C standard library (plus some important data structures missing in the libc).

More than two years ago the OCaml community decided to start the development of a library containing all the conveniences that are missing in the standard library. The project is OCaml Batteries Included and I'd like to introduce the reader with a series of posts, aimed to cast a light on various aspects of the library, without pretending to be an exhaustive tutorial.

The posts will be targeted at novice OCaml programmers because I think that an experienced OCaml hacker already uses "Batteries" or, in any case, he understand the library API and doesn't need help from this blog.

Before starting with the (boring) installation details, I want to give you a taste of Batteries, to show how a simple task could be written in a more natural way using Batteries modules, in comparison with a vanilla implementation. Let's take this simple task: we want to read a file by lines and print on the terminal only those lines containing a particular substring.

A simple and actually working solution is proposed by the PLEAC-Objective CAML project, it's the very first example of the file access section. Here is the proposed code:

let () =
  let in_channel = open_in "/usr/local/widgets/data" in
    while true do
      let line = input_line in_channel in
        ignore (Str.search_forward (Str.regexp_string "blue") line 0);
        print_endline line
      with Not_found -> ()
  with End_of_file ->
    close_in in_channel

Now let's rephrase using Batteries:

  (fun l ->
    if BatString.exists l "blue"
    then print_endline l)
  (open_in "/usr/local/widgets/data" |> BatIO.lines_of)

The result is the same, but the code is much cleaner and far more idiomatic for a functional language.

Next time we will see how to install OCaml and Batteries, under Linux of course, but hopefully even under Windows.