New to OCaml? We recommend checking out A Tour of OCaml to get up to speed.

Local development

To run the code for your challenge locally, you’ll need opam and dune installed. Our test runners use Dune v3.16 (as of September 2024).

The script for your challenge (./your_program.sh) will run your code using these tools. It will look something like this:

#!/bin/sh

dune build --build-dir /tmp/redis
exec /tmp/redis/default/main.exe "$@"

File structure

  • The files for your solution are placed in the src/ directory.
  • src/main.ml is the entry point for your OCaml program.

Adding more files

You can organize your code by adding more .ml files in the src/ directory. The test runner will include them when building and running your code.

For example, if you add a file at src/foo.ml, you can reference it in main.ml like this:

Adding dependencies

If you’re looking for OCaml libraries, you can browse the opam package repository.

1

Specify dependencies

You need to specify dependencies in both the dune-project and dune files.

For example, to add the yojson library for handling JSON, first update dune-project as follows:

(generate_opam_files true)

(package
   (name codecrafters_redis)
+  (depends yojson)
   (version 0.1))

Then, update the dune file to include yojson as a library:

(executable
  (name main)
- (libraries unix))
+ (libraries unix yojson))
For more details, check the OCaml documentation on Adding a Dependency.
2

Install dependencies

You need to regenerate the .opam file from dune-project before installing dependencies.

First, run this command to update the .opam file:

dune build
If you’ve already used the library in an .ml file, dune build will exit with an error. This is okay — it’ll still update the .opam file (required for the next step).

Then, run this command to install the dependencies:

opam install . --deps-only
3

Use dependencies

Here’s an example of how to use the yojson library:

open Yojson.Basic

let () =
  {| { "challenge": "Build your own Redis", "language": "OCaml" } |}
  |> from_string
  |> Util.member "language"
  |> Util.to_string
  |> print_endline

(* This will print "OCaml" *)