Fast and reliable programs with OCaml
Pattern Matching
OCaml's version of switch
is match
. Here, low numbers print as words, but anything else uses the built-in string_of_int
function to display a decimal:
let to_string x = match x with | 1 -> "one" | 2 -> "two" | n -> string_of_int n
You can also match on strings, variants, records, and other complex values. OCaml will always check that you have covered every case. This is the key to its reliability.
Pattern matching can also be used in anonymous functions, like this:
let to_string = function | 1 -> "one" | 2 -> "two" | n -> string_of_int n
Anonymous functions are like lambda expressions in Python; you'll often see this shorter form.
Data Structures
OCaml allows you to define both variants (unions representing a choice of alternatives) and records (structs or named tuples holding several values at once). For example, the result of a download can be declared as a variant:
type download_result = | Success of filepath | Network_error of string | Aborted_by_user
This ensures that everywhere a URL downloads, it also handles a failed download (typically by displaying the error to the user) or a canceled download (not an error).
It's used as follows:
match download url with | Success file -> process file | Network_error msg -> alert msg | Aborted_by_user -> ()
Notice that each case can only access the appropriate value: You can't accidentally try to use file
if the download failed or display msg
if it succeeded.
A record joins together several pieces of information:
type program = { name : string; homepage : url option; }
Records and variants can be combined. In fact, the type url option
in this record is itself a variant, because the homepage
field can be either None
or Some
URL. By making optional types explicit, OCaml completely avoids Java's dreaded NullPointerException
(or C's segfault
).
OCaml also supports polymorphic (generic) types:
type 'a result = | Success of 'a | Error of exn
These allow you to construct whole families of types (e.g., int
result, string
result, or program
result), while still writing generic code that can work on any of them, such as this function to return a result's value (or throw its exception):
let success = function | Success value -> value | Error ex -> raise ex
You don't have to declare variants before use; you can use the syntax `<tag>
to let OCaml infer variant types automatically (examples below).
Loops
An unusual feature of functional programming is that loops are often written in a tail-recursive style (Listing 1). This prompts the user with a question, returning `yes
if the user enters y or yes and so on.
Listing 1
Tail-Recursive Loops
If the user doesn't provide a valid response, it calls itself recursively to ask again. Because this recursive call is always the last thing the function does, OCaml does not need to store the return address on the stack, and you can loop any number of times without running out of memory. Effectively, the function call turns into a goto.
OCaml does support more traditional for
and while
loops, too, but the recursive form can be more elegant.
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
-
Juno Tab 3 Launches with Ubuntu 24.04
Anyone looking for a full-blown Linux tablet need look no further. Juno has released the Tab 3.
-
New KDE Slimbook Plasma Available for Preorder
Powered by an AMD Ryzen CPU, the latest KDE Slimbook laptop is powerful enough for local AI tasks.
-
Rhino Linux Announces Latest "Quick Update"
If you prefer your Linux distribution to be of the rolling type, Rhino Linux delivers a beautiful and reliable experience.
-
Plasma Desktop Will Soon Ask for Donations
The next iteration of Plasma has reached the soft feature freeze for the 6.2 version and includes a feature that could be divisive.
-
Linux Market Share Hits New High
For the first time, the Linux market share has reached a new high for desktops, and the trend looks like it will continue.
-
LibreOffice 24.8 Delivers New Features
LibreOffice is often considered the de facto standard office suite for the Linux operating system.
-
Deepin 23 Offers Wayland Support and New AI Tool
Deepin has been considered one of the most beautiful desktop operating systems for a long time and the arrival of version 23 has bolstered that reputation.
-
CachyOS Adds Support for System76's COSMIC Desktop
The August 2024 release of CachyOS includes support for the COSMIC desktop as well as some important bits for video.
-
Linux Foundation Adopts OMI to Foster Ethical LLMs
The Open Model Initiative hopes to create community LLMs that rival proprietary models but avoid restrictive licensing that limits usage.
-
Ubuntu 24.10 to Include the Latest Linux Kernel
Ubuntu users have grown accustomed to their favorite distribution shipping with a kernel that's not quite as up-to-date as other distros but that changes with 24.10.