3 ms·
OCaml has recently interested me for being one of the few languages that: - Compiles to a binary - Achieves good speed - Is functional, while accommodating imp
by shadowofneptune 5y ago
OCaml has recently interested me for being one of the few languages that:
- Compiles to a binary
- Achieves good speed
- Is functional, while accommodating imperative styles.
- Has a static type
In particular, it interests me because of how Forth or a threaded code-based VM could be implemented in it. You could implement the operations of such a machine with a bunch of individual function calls, but that's slow and rather unnecessary. A jump to the next VM instruction's code is what you want instead.
Switch statements or pointers to labels are what are often used, but that means you end up with hundreds or even thousands of lines of code which cannot be split into modules. The solution OCaml and other functional languages provide involves tail-call optimization:
let rec first x = print_endline "foo" ; second(x)
and second x = print_endline "bar" ; first(x);;
first 1;;
In a usual compiled language, these two functions would only be able to print 'foobar' a few hundred or thousand times before causing a stack overflow. In a language like OCaml this can run forever, and quickly too. This allows for what this web page calls continuation-passing threaded code:
https://www.complang.tuwien.ac.at/forth/threaded-code.html https://www.complang.tuwien.ac.at/forth/threaded-code.html
I have mocked up the concept in lua, an imperative language with tail call optimization, and it was quite easy to implement a basic Forth while keeping the code legible. To take the idea further OCaml feels like a good choice. If anyone has experience with OCaml, or any warnings, it would be helpful.