InnocentZero's Treasure Chest

HomeFeedAbout MeList of interesting people

26 Jun 2025

Experiments with OCaml

OCaml

I feel embarrassed to admit that I've never written a real project in OCaml. So let's settle that today. I'll be doing this series to learn both jujutsu and OCaml properly. I'll push it to my codeberg once I've learned how to do that. So keep following along!

Let's begin!

Getting the book

Huge thanks to my friend for providing me with a copy of Nora Sandler's Writing a C compiler. That's the book I'm following.

Editor setups

Obviously I haven't done this properly either. I'll start with Emacs. For OCaml, I'll be using the wonderful neocaml mode by Bozhidar Batsov, it's available on github!

Here's my config using elpaca

(use-package
 neocaml
 :ensure (neocaml :type git :host github :repo "bbatsov/neocaml")
 :hook (neocaml-mode . prettify-symbols-mode)
 (neocaml-mode
  . (lambda () (setq-local indent-line-function 'indent-relative))))

Make sure you add ocamllsp to the list of eglot-server-programs.

I'll configure helix later, but all that's needed is to install ocamllsp.

jujutsu

Now we set up the repo. How to do that? Steve Klabnik's guide comes to rescue.

As an aside, threw in a quick jj config for starship. Check jj's wiki out!

Run jj git init. This will create the repo.

OCaml

Now we run dune init project compiler . to initialize project compiler in the current directory. It creates bin and lib by default.

First baby steps

Now we need to be able to start lexing the program, so we need to write a regex engine in OCaml. It's fine if it's inefficient, that's not the point right now really.

Actually, let's not bother with a regex engine. That'll be traumatizing. I'm trying to find existing implementations in the standard library, but everything looks too old to me.

Nvm, just used Str module, and it works. It has decent support for ocaml, so beginner things would work.

As an aside, I found the API particularly distasteful. What is this weird ass method of finding the string as a consequence of a side effect to a totally different function call? Surely there has to be a better way than this.

Setting up user

Figured out I'd create a commit now. Set my user name and email. Also, for some reason it was tracking the build files, but I easily untracked them using jj files untrack _build. Also, it respects gitignore, so keep that in mind.

As an aside, setting up helix was pretty simple as well. It'll do most things, just configure the formatter. That's equivalent to the command of ocamlformat - --impl.

Tags: programming ocaml

Other posts
Creative Commons License
This website by Md Isfarul Haque is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.