Skip to main content

OCaml

OCaml is a general-purpose, functional programming language that extends the Caml dialect of ML with object-oriented features. It is known for its powerful type system, pattern matching, and functional programming capabilities.

LiveCodes compiles OCaml code to JavaScript using the ReScript compiler. OCaml in LiveCodes supports JSX via a ReasonReact-compatible syntax.

Usage

Demo

show code
import { createPlayground } from 'livecodes';

const options = {
"template": "ocaml"
};
createPlayground('#container', options);

Module Imports

npm modules can be imported as described in the section about module resolution. External modules can be bound using [@bs.module].

OCaml React (JSX)

LiveCodes supports JSX in OCaml using a ReasonReact-compatible syntax. Components use [@@react.component] and the [@JSX] attribute.

module App =
struct
let make ~name =
let (count, setCount) = React.useState ((fun _ -> 0) [@bs]) in
let times = string_of_int count ^ " times" in

((div ~className: "container"
~children:[
((h1 ~children: [React.string ("Hello, " ^ name ^ "!")] ()) [@JSX]);
((p ~children: [React.string ("You clicked " ^ times)] ()) [@JSX]);
((button
~onClick:((fun _ -> setCount ((fun _ -> count + 1) [@bs])) [@bs])
~children:[React.string "Click me"] ())
[@JSX]);
] ()) [@JSX]) [@@react.component]
end

let _ =
match ReactDOM.querySelector "#app" with
| ((Some app) [@explicit_arity]) ->
ReactDOM.render ((App.createElement ~name: "OCaml" ~children:[] ()) [@JSX]) app
| None -> ()
warning

OCaml React does not support React 19. Use an import map (in custom settings) to pin React to v18:

Custom Settings
{
"imports": {
"react": "https://esm.sh/[email protected]",
"react/": "https://esm.sh/[email protected]/",
"react-dom": "https://esm.sh/[email protected]"
}
}

Language Info

Name

ocaml

Extensions

.ml, .mli

Editor

script

Compiler

ReScript compiler

Version

rescript: v9.1.2

Code Formatting

Not supported.

Starter Template

https://livecodes.io/?template=ocaml