The bitter aftertaste of syntactic sugar
I am not particularly fond of syntactic sugar. Granted, there's the bare minimum of sweetness that a language should have, but anything beyond that — no matter how tempting it is to include it in the language definition — is only likely to bring you pain in the long term (if you're looking for an example, then look no further than Perl, whose sugary excesses resulted in a language whose programmes have been described as "looking like an explosion in a punctuation factory").
The Ocaml language makes for an interesting case study in this regard. While the core language is sprinkled with a fair share of sugary treats*, it still makes for a reasonably lean language. However, this does not mean that a programmer can't use their favourite non-standard candy (be it list comprehensions, for-in loops, memoization, or whatever else) with Ocaml. So, how can we solve this apparent dietary paradox?
Enter Camlp4.
Camlp4 (and Camlp5, which confusingly is not the successor, but rather the continuation of the old pre-3.10 Camlp4) is one of those tools whose significance is understated and often completely overlooked by newcomers to the Ocaml language. So what does it do? In brief, it allows the programmer to create syntax extensions to the Ocaml language in such a way that they integrate seamlessly with the core language. Think of it as the C preprocessor on steroids.
If you're curious, check this list for just some examples of the syntax extensions that people have created for Ocaml. Another great example is of course PG'OCaml, which extends Ocaml's syntax with the ability to directly embed SQL statements, with compile-time checking of consistency between the Ocaml code and the PostgreSQL database (which is of course contacted at compile-time: think how cool that is!).
On a deeper level, tools like Camlp4 allow the definition of languages whose core is lean and mean, but without sacrificing the possibility of using syntactic sugar when it is justified. And this is for me the greatest lesson of Camlp4 to the designers of future languages.
*Check this interesting comparison of Ocaml and Standard ML for more details. You'll see that while Ocaml is "sweeter" than SML, most of Ocaml's sugar additions tend to be well justified.

Comments