Been exploring ocaml recently and was trying to implement a very basic REPL using recursive functions.
The usual REPL code we write are as below
Though in OCaml we usually don’t write imperative code, so trying that with functions would look like
This code looks pretty intuitive until we look at the match here, there is a bug here. Formatting this snippet we will get the below
We can see that the program_loop() invocation has gone to the last catch of match. The semicolon does not help here as expected.
To make this work what we need to do is
This is one of the gotchas of match in OCaml. Took me sometime to figure this and had help from the community as well. For a beginner this can be trippy.
The final snippet that I implemented is as below. It’s a simple program which runs and keeps taking input and give results. It’s self expalanatory so I will leave it to the reader to figure out the rest 😄