Fast and reliable programs with OCaml
Oasis
Static typing, type checking, and low memory usage make this easy-to-learn language a strong candidate for application development.
OCaml is a statically typed programming language with a focus on correctness and speed. First released in 1996 as "Objective Caml," OCaml extended the older Caml language with object-oriented features. OCaml [1] is now mature, stable, and well documented.
It supports both functional and imperative programming styles, making it a good choice for Python, C, or Java programmers interested in writing more reliable software.
Syntax Basics
OCaml's syntax can look a little alien at first. For example, here's a complete OCaml program:
let x = 3 let y = 4 let () = Printf.printf "%d + %d = %d\n" x y (x + y)
The let
declarations are evaluated in order (the compiler infers the types automatically). Expressions that don't return any meaningful value, such as printf
, return the empty tuple ()
, which is called unit
, similar to void
in C or Java.
Assigning the final result to ()
causes the compiler to check that the expression really does return unit
and you're not ignoring something important. Printf.printf
means the printf
function inside the Printf
module. Module names always start with a capital letter in OCaml.
Functions
Functions are also defined with the let
keyword:
let add x y = x + y
Unlike C, Python, and Java, OCaml does not use parentheses around arguments and does not have a return
keyword; it simply evaluates the function's body as a single expression. In OCaml, even an if
… then
construct is an expression and produces a value, as in this factorial definition:
let rec fact n = if n = 1 then 1 else n * fact (n - 1)
When defining a recursive function, such as factorial, you must use the rec
keyword to allow the function to call itself. Without this, the name fact
wouldn't be in scope within the body.
Partial Functions
OCaml functions really only take a single argument. A two-argument function conceptually takes its first argument and returns a new function to handle the second. This process is known as currying. These expressions are equivalent:
add x y (add x) y
For example, add 5
is a function that takes an integer and adds 5 to it:
let add_five = add 5 let six = add_five 1
You'll often see partial application of a curried function to make code more concise. These are equivalent:
let hi x = printf "Hi, %s!\n" x let hi = printf "Hi, %s!\n"
In both cases, hi
is a function with type string -> unit
(it takes a string and returns nothing). Partial application is particularly useful with loops. For example, to print each item in a list, you can do:
List.iter (Printf.printf "- %s\n") ["foo"; "bar"]
The first argument to List.iter
is a function to be invoked on each item in the list. Partial application saves having to define a new function.
Curried functions allow some useful tricks. Consider the pipe operator, which can be defined as:
let (|>) x f = f x
This takes an argument and a function and calls the function with the argument. It works a bit like a pipe in the shell:
["foo"; "bar"] |> List.map String.uppercase |> List.iter (Printf.printf "- %s\n")
List.map
produces a new list by using the given function to transform each item.
This code converts each string to upper case and then prints it. Can you see how it works? Hint: x |> f |> g
is interpreted as (x |> f) |> g
. The pipe operator can make function chains easier to read, and it's also a built-in operator in later versions of OCaml.
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters
Support Our Work
Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.
News
-
Canonical Bumps LTS Support to 12 years
If you're worried that your Ubuntu LTS release won't be supported long enough to last, Canonical has a surprise for you in the form of 12 years of security coverage.
-
Fedora 40 Beta Released Soon
With the official release of Fedora 40 coming in April, it's almost time to download the beta and see what's new.
-
New Pentesting Distribution to Compete with Kali Linux
SnoopGod is now available for your testing needs
-
Juno Computers Launches Another Linux Laptop
If you're looking for a powerhouse laptop that runs Ubuntu, the Juno Computers Neptune 17 v6 should be on your radar.
-
ZorinOS 17.1 Released, Includes Improved Windows App Support
If you need or desire to run Windows applications on Linux, there's one distribution intent on making that easier for you and its new release further improves that feature.
-
Linux Market Share Surpasses 4% for the First Time
Look out Windows and macOS, Linux is on the rise and has even topped ChromeOS to become the fourth most widely used OS around the globe.
-
KDE’s Plasma 6 Officially Available
KDE’s Plasma 6.0 "Megarelease" has happened, and it's brimming with new features, polish, and performance.
-
Latest Version of Tails Unleashed
Tails 6.0 is based on Debian 12 and includes GNOME 43.
-
KDE Announces New Slimbook V with Plenty of Power and KDE’s Plasma 6
If you're a fan of KDE Plasma, you'll be thrilled to hear they've announced a new Slimbook with an AMD CPU and the latest version of KDE Plasma desktop.
-
Monthly Sponsorship Includes Early Access to elementary OS 8
If you want to get a glimpse of what's in the pipeline for elementary OS 8, just set up a monthly sponsorship to help fund its continued existence.