Wiki

Clone wiki

newref / Home

Problem

OCaml uses ! before a variable to show that it is mutable (called a ref):

let s = ref true in
if !s then print_endline "s is true"

This is all nice and dandy if you have not been programming in any other language, but can be a pain if you are used to C, C++, Java, Javascript or any other language where ! means "not". It makes the difference between reading "s is true" or "s is not true" in the above example.

Often, you are even stuck writing both C and OCaml at the same time, for example while wrapping a library, leaving you confused in both cases.

Solution

Using the awesomeness called camlp4, I've written an alternative syntax for refs, namely the dollar sign. The above example will then become:

let s = ref true in
if $s then print_endline "s is true"

Using this syntax will let you program in OCaml without going insane. (Well, not because of *this* aspect of the language, anyway)

To try it out, get the source (see "hg clone" above), and do

make
./testref

About camlp4

I hope that this can serve as a minimal example of camlp4 as well. Since this is my first attempt at it, those few lines are probably riddled with bugs. Let me know if you find any!

Updated