OCaml
Online OCaml Compiler
main.ml is compiled to native code with ocamlopt from OCaml 5.5, then run. read_line flushes the output first, so a prompt written with print_string shows before the program waits for you.
Try it aboveHow OCaml runs here
- Versions
- OCaml 5.5
- Build
ocamlopt -o a.out main.ml- Run
./a.out- Limits per run
- 256 MB memory, 15 s of CPU time on half a core, 2 MB of output
- Time
- Up to 10 minutes a run (30 on a paid plan); waits 2 minutes for input (5 on a paid plan)
- Sandbox
- Each run gets its own Linux sandbox with no network access. Text files your program writes next to your code open as new tabs.
An OCaml program that reads input
This main.ml counts the words in a sentence with a Hashtbl, then sorts them by count and name with the pipe operator:
let () = print_string "Enter a sentence: "; let line = read_line () in let words = String.split_on_char ' ' (String.lowercase_ascii line) |> List.filter (fun w -> w <> "") in let counts = Hashtbl.create 16 in List.iter (fun w -> Hashtbl.replace counts w (1 + Option.value ~default:0 (Hashtbl.find_opt counts w))) words; Hashtbl.fold (fun w n acc -> (w, n) :: acc) counts [] |> List.sort (fun (a, x) (b, y) -> if x <> y then compare y x else compare a b) |> List.iter (fun (w, n) -> Printf.printf "%-6s %d\n" w n)
$ ocamlopt -o a.out main.ml && ./a.out Enter a sentence: the cat and the dog and the bird the 3 and 2 bird 1 cat 1 dog 1
Reading input in OCaml
- read_line () returns one line without its newline. Convert it with int_of_string or float_of_string, which raise Failure on bad input; int_of_string_opt returns None instead.
- Scanf.scanf " %d" (fun n -> n) reads a number and skips the spaces and newlines before it.
- Arguments from Run settings are in Sys.argv, after the program name.
What isn’t available here
- opam packages and dune: only the standard library is there, so no Core, Lwt or Yojson.
- Several files: ocamlopt compiles main.ml alone, so modules in other .ml files aren’t linked. Put them in main.ml as module Name = struct … end.
Errors you’ll see
- “Error: This constant has type string but an expression was expected of type int” A type mismatch, reported at compile time with the line and characters.
- “Fatal error: exception Failure("int_of_string")” int_of_string got text that isn’t a number.
- “Warning 8: this pattern-matching is not exhaustive” A match misses a case. It compiles, but fails at run time if that case comes.
Questions
Which OCaml version is this?
OCaml 5.5, compiling main.ml to native code with ocamlopt.
How do I read input in OCaml?
let line = read_line () in … for a line of text, int_of_string (read_line ()) for a number. Type the input in the terminal while the program runs.
Can I use Core or other opam libraries?
No. Only the OCaml standard library is installed.