OCaml facts for kids
![]() |
|
Paradigms | Multi-paradigm: functional, imperative, modular, object-oriented |
---|---|
Family | ML: Caml |
Designed by | Xavier Leroy, Jérôme Vouillon, Damien Doligez, Didier Rémy, Ascánder Suárez |
Developer | Inria |
First appeared | 1996 |
Stable release | |
Typing discipline | Inferred, static, strong, structural |
Implementation language | OCaml, C |
Platform | IA-32, x86-64, Power, SPARC, ARM 32-64, RISC-V |
OS | Cross-platform: Linux, Unix, macOS, Windows |
License | LGPLv2.1 |
Filename extensions | .ml, .mli |
Influenced by | |
C, Caml, Modula-3, Pascal, Standard ML | |
Influenced | |
ATS, Coq, Elm, F#, F*, Haxe, Opa, Rust, Scala | |
|
OCaml (pronounced "oh-KAM-uhl") is a computer programming language. It's a "general-purpose" language, meaning you can use it for many different kinds of computer programs. It's also a "high-level" language, which means it's easier for humans to read and write than "low-level" languages.
OCaml lets you write programs in different styles, like functional, imperative, and object-oriented programming. It was created in 1996 by a team of designers.
The OCaml "toolchain" includes many helpful tools. These include an interactive tool to test code, a "compiler" that turns your code into a program, and a "debugger" to help find mistakes. OCaml was first used for checking mathematical proofs. Today, it's used for many things, like building computer systems, making websites, and creating financial tools.
OCaml is a free and open-source software project. This means anyone can use, change, and share it. It is mainly kept up-to-date by a group called Inria in France. Other languages like F# and Scala have used ideas from OCaml.
Contents
How OCaml Works
OCaml is known for its special "type system." This system helps prevent many common errors in programs. It checks your code before it runs to make sure different parts of your program fit together correctly.
Smart Type Checking
OCaml's compiler is very smart. It can often figure out the "type" of your data by itself. For example, it knows if something is a number or text without you having to tell it. This saves you time because you don't have to write down every type, unlike in languages like Java.
Fast and Reliable Programs
OCaml helps programmers create reliable software. Because its type system catches errors early, programs tend to have fewer problems when they run. OCaml is also designed to make programs run very fast. It can be almost as fast as programs written in C, which is known for its speed.
The Story of OCaml
OCaml's history goes back to the 1970s and 1980s. It started with a language called ML.
Building the ML Language
A British computer scientist named Robin Milner worked on "theorem provers." These are computer programs that check mathematical proofs. Milner found that his provers sometimes made mistakes. To fix this, he created a language called ML (Meta Language). ML was designed to only allow valid proofs to be built.
Later, researchers in France became interested in ML. They developed a way to make ML programs run faster. This led to the creation of the "Categorical Abstract Machine" (CAM).
The First Caml Programs
The first version of Caml was made in 1987 by a team at INRIA. It was improved over several years.
Caml Light: A Smaller Version
In the early 1990s, Xavier Leroy created a new version called Caml Light. This version was smaller and could run on desktop computers. It also had a system to manage computer memory automatically, called a "garbage collector."
Caml Special Light: Getting Faster
In 1995, Xavier Leroy released Caml Special Light. This version included a new "native-code" compiler. This compiler made OCaml programs much faster, similar to languages like C++. It also added a powerful "module system" to help build larger programs more easily.
Objective Caml: Adding Objects
Then, in 1996, Objective Caml was released. This version added "object-oriented" features to the language. This meant programmers could organize their code using "objects" and "classes." Objective Caml was later renamed to just OCaml in 2011.
OCaml Today
OCaml continues to be updated and improved. Recent updates have made it even more flexible and able to handle multiple tasks at once. Many developers from different organizations work together to improve OCaml.
What OCaml Can Do
OCaml has many cool features that make it a powerful language for programmers.
- Smart Type System: It checks your code carefully before it runs.
- Type Inference: It often figures out data types by itself.
- Pattern Matching: This is a neat way to check data and run different code based on what the data looks like.
- Automatic Memory Management: It cleans up memory automatically, so programmers don't have to worry about it.
- Connecting to C: OCaml can easily connect with programs written in the C language. This means you can use existing C code in your OCaml projects.
The OCaml software package also comes with useful tools:
- Tools for analyzing and understanding code.
- A Debugger to help you find and fix errors in your programs.
- A tool to create documentation for your code.
- A profiler to see how fast different parts of your program run.
- Many general-purpose libraries (collections of ready-to-use code).
OCaml programs can run on many different computer systems. This includes Linux, Windows, and macOS.
Trying Out OCaml Code
You can easily try OCaml code using its interactive tool called the "REPL." It's like a calculator for code.
To start it, you type:
$ ocaml
Objective Caml version 3.09.0
#
Then you can type code at the "#" prompt. For example, to calculate 1+2*3:
# 1 + 2 * 3;;
- : int = 7
OCaml figures out the answer is 7 and that it's an "int" (a whole number).
Hello World!
Here's a simple program that prints "Hello World!":
print_endline "Hello World!"
You can save this as `hello.ml`. To turn it into a program you can run, you use a command like this: $ ocamlc hello.ml -o hello Then you can run it:
$ ./hello
Hello World!
$
Handling Missing Values (Option Type)
OCaml has a special way to handle values that might not be there. It uses something called the `option` type. A value can be `Some` (meaning it has a value inside) or `None` (meaning it's empty).
# Some 42;;
- : int option = Some 42
# None;;
- : 'a option = None
Here's a function that takes an `option` and gives you the number inside, or an empty string if there's no number:
let extract o =
match o with
| Some i -> string_of_int i
| None -> "";;
# extract (Some 42);;
- : string = "42"
# extract None;;
- : string = ""
Adding Numbers in a List
Lists are a basic way to store groups of items in OCaml. Here's how you can add up all the numbers in a list using a "recursive" function (a function that calls itself):
let rec sum integers = (* 'rec' means this function calls itself. *)
match integers with
| [] -> 0 (* If the list is empty, the sum is 0. *)
| first :: rest -> first + sum rest;; (* Otherwise, add the first number to the sum of the rest. *)
# sum [1;2;3;4;5];;
- : int = 15
There are also shorter ways to do this using built-in functions:
let sum integers =
List.fold_left (+) 0 integers
This version does the same thing but is more compact.
Sorting a List (Quicksort)
OCaml is great for writing sorting algorithms. Here's a simple version of "quicksort" that sorts a list of numbers:
let rec qsort = function
| [] -> []
| pivot :: rest ->
let is_less x = x < pivot in
let left, right = List.partition is_less rest in
qsort left @ [pivot] @ qsort right
This code picks a "pivot" number, then splits the rest of the list into numbers smaller than the pivot and numbers larger than the pivot. It then sorts those two smaller lists and puts everything back together.
Making Graphics (Triangle)
OCaml can also be used to create graphics. This program draws a spinning triangle using a graphics library called OpenGL:
let () =
ignore (Glut.init Sys.argv);
Glut.initDisplayMode ~double_buffer:true ();
ignore (Glut.createWindow ~title:"OpenGL Demo");
let angle t = 10. *. t *. t in
let render () =
GlClear.clear [ `color ];
GlMat.load_identity ();
GlMat.rotate ~angle: (angle (Sys.time ())) ~z:1. ();
GlDraw.begins `triangles;
List.iter GlDraw.vertex2 [-1., -1.; 0., 1.; 1., -1.];
GlDraw.ends ();
Glut.swapBuffers () in
GlMat.mode `modelview;
Glut.displayFunc ~cb:render;
Glut.idleFunc ~cb:(Some Glut.postRedisplay);
Glut.mainLoop ()
This program can be compiled and run to show a simple animated graphic.
Fibonacci Sequence
The Fibonacci sequence is a series of numbers where each number is the sum of the two before it (e.g., 0, 1, 1, 2, 3, 5, 8...). Here's an OCaml function to calculate a Fibonacci number:
let fib n =
let rec fib_aux m a b =
match m with
| 0 -> a
| _ -> fib_aux (m - 1) b (a + b)
in fib_aux n 0 1
Functions That Use Other Functions
In OCaml, functions can take other functions as input or even give back a new function as a result. This is called "higher-order functions." For example, this `twice` function takes any function `f` and creates a new function that applies `f` two times:
let twice (f : 'a -> 'a) = fun (x : 'a) -> f (f x);;
let inc (x : int) : int = x + 1;;
let add2 = twice inc;;
let inc_str (x : string) : string = x ^ " " ^ x;;
let add_str = twice(inc_str);;
# add2 98;;
- : int = 100
# add_str "Test";;
- : string = "Test Test Test Test"
You can even apply `twice` to itself!
# let fourtimes f = (twice twice) f;;
val fourtimes : ('a -> 'a) -> 'a -> 'a = <fun>
# let add4 = fourtimes inc;;
val add4 : int -> int = <fun>
# add4 98;;
- : int = 102
Languages Based on OCaml
OCaml has inspired other programming languages.
- F# is a language for the .NET platform that is based on OCaml.
- Reason is another way to write OCaml code. It was created by Facebook and can turn OCaml code into native programs or JavaScript for websites.
Software Made with OCaml
Many different software programs and tools are built using OCaml. Here are some examples:
- Coq: A system for managing formal mathematical proofs.
- The web version of Facebook Messenger.
- Flow: A tool from Facebook that checks JavaScript code for errors.
- Hack: A programming language from Facebook that adds static types to PHP.
- Haxe: A programming language compiler.
- Infer: Another static checker from Facebook that finds bugs in apps for iOS and Android.
- MirageOS: A special kind of operating system written entirely in OCaml.
- MLdonkey: A program for sharing files.
- Opa: A programming language for building websites.
- Tezos: A platform for smart contracts (like digital agreements).
- Unison: A program that keeps files synchronized between different folders or computers.
- The official tool for running WebAssembly code, which is used in web browsers.
Who Uses OCaml?
Many companies use OCaml for their projects.
- Bloomberg L.P.: A financial data company that created a tool to turn OCaml code into JavaScript.
- Citrix Systems: Uses OCaml in its XenServer software for managing virtual computers.
- Facebook: Uses OCaml for several of its important tools like Flow, Hack, and Infer.
- Jane Street Capital: A trading firm that uses OCaml as its main programming language.
- Docker: Uses OCaml in its desktop applications for macOS and Windows.