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 17. Data Serialization with S-Expressions

S-expressions are nested parenthetical expressions whose atomic values are strings. They were first popularized by the Lisp programming language in the 1960s. They have remained one of the simplest and most effective ways to encode structured data in a human-readable and editable form.

There’s a full definition of s-expressions available online. An example s-expression might look like this:

Scheme

(this (is an) (s expression))

S-expressions play a major role in Core, effectively acting as the default serialization format. Indeed, we’ve encountered s-expressions multiple times already, including in Chapter 7, Chapter 9, and Chapter 10.

This chapter will go into s-expressions in more depth. In particular, we’ll discuss:

  • The details of the s-expression format, including how to parse it while generating good error messages for debugging malformed inputs

  • How to generate s-expressions from arbitrary OCaml types

  • How to use custom type annotations to control the exact printing behavior for s-expression converters

  • How to integrate s-expressions into your interfaces, in particular how to add s-expression converters to a module without breaking abstraction boundaries

We’ll tie this together at the end of the chapter with a simple s-expression formatted configuration file for a web server

Basic Usage

The type used to represent an s-expression is quite simple:

OCaml

module Sexp : sig
  type t =
  | Atom of string
  | List of t list
end

An s-expression can be thought ...

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