Programming Books

6 Excellent Free Books to Learn OCaml

Last Updated on June 28, 2024

Caml is a general-purpose, powerful, high-level programming language with a large emphasis on speed and efficiency. A dialect of the ML programming language, it supports functional, imperative, and object-oriented programming styles. Caml has been developed and distributed by INRIA, a French research institute, since 1985.

The OCaml system is the main implementation of the Caml language. It has a very strong type-checking system, offers a powerful module system, automatic memory management, first-class functions, and adds a full-fledged object-oriented layer. OCaml includes a native-code compiler supporting numerous architectures, for high performance; a bytecode compiler, for increased portability; and an interactive loop, for experimentation and rapid development. OCaml’s integrated object system allows object-oriented programming without sacrificing the benefits of functional programming, parametric polymorphism, and type inference. The language is mature, producing efficient code and comes with a large set of general purpose as well as domain-specific libraries.

OCaml is often used for teaching programming, and by large corporations. OCaml benefits from a whole range of new tools and libraries, including OPAM (package manager), optimizing compilers, and development tools such as TypeRex and Merlin.

OCaml was written in 1996 by Xavier Leroy, Jérôme Vouillon, Damien Doligez, and Didier Rémy at INRIA in France.


1. Real World OCaml by Yaron Minsky, Anil Madhavapeddy, Jason Hickey

Real World OCaml

Real World OCaml introduces the reader to OCaml, an industrial-strength programming language designed for expressiveness, safety, and speed. Through the book’s many examples, the reader learns how OCaml stands out as a tool for writing fast, succinct, and readable code. The book offers a clear guide to what you need to know to use OCaml effectively in the real world.

The book starts with a gentle introduction to OCaml. Part 2 of the book (“tools and techniques”) demonstrates how to perform practical tasks such as: parse command-lines, read and write JSON formatted data and handle concurrent I/O; while part 3 dives into low-level detail including: interfacing to C and understanding the GCC and compiler toolchain. It’s aimed at programmers who have some experience with conventional programming languages, but not specifically with statically typed functional programming.

Chapters include:

  • A Guided Tour – gives an overview of OCaml by walking through a series of small examples that cover most of the major features of the language.
  • Variables and Functions – covers OCaml’s approach to variables and functions in some detail, starting with the basics of how to define a variable, and ending with the intricacies of functions with labeled and optional arguments.
  • Lists and Patterns – goes into more detail about these two common elements of programming.
  • Files, Modules, and Programs – shows the reader how to build an OCaml program from a collection of files, as well as the basics of working with modules and module signatures.
  • Records – in depth treatment covering the details of how records work, as well as advice on how to use them effectively in software designs.
  • Variants – explores one of the most useful features of OCaml.
  • Error Handling – discusses some of the different approaches in OCaml to handling errors, and give some advice on how to design interfaces that make error handling easier.
  • Imperative Programming – walks the reader through OCaml’s imperative features, and help use them to their fullest.
  • Functors – functions from modules to modules which can be used to solve a variety of code-structuring problems.
  • First-Class Modules – ordinary values that can be created from and converted back to regular modules.
  • Objects – introduces the reader to OCaml objects and subtyping.
  • Classes – introduces the reader to classes and inheritance.
  • Maps and Hash Tables – a map is an immutable tree-based data structure where most operations take time logarithmic in the size of the map, whereas a hash table is a mutable data structure where most operations have constant time complexity. This chapter describes both of these data structures in detail and provides advice as to how to choose between them.
  • Command-Line Parsing – construct basic and grouped command-line interfaces, build simple equivalents to the cryptographic md5 and shasum utilities, and shows how functional combinators can be used to declare complex command-line interfaces in a type-safe and elegant way.
  • Handling JSON Data – introduces the reader to a couple of new techniques.
  • Parsing with OCamilex and Menhir – OCamilex, replaces lex, and ocamlyacc and menhir, which replace yacc. This chapter explores these tools and the implementation of a parser for the JSON serialization format.
  • Data Serialization with S-Expressions – goes into s-expressions in more depth.
  • Concurrent Programming with Async – covers the Async library, which offers a hybrid model that aims to provide the best of both worlds.
  • Foreign Function Interface – show how to call routines in C libraries directly from OCaml code, how to build higher-level abstractions in OCaml from the low-level C bindings, and work through some full examples for binding a terminal interface and UNIX date/time functions.
  • Memory Representation of Values – describes the runtime format of individual OCaml variables.
  • Understanding the Garbage Collector.
  • The Compiler Frontend: Parsing and Type Checking – compilation pipeline and what each stage represents, source preprocessing via Camlp4 and the intermediate forms, and type-checking process, including module resolution.
  • The Compiler Backend: Bytecode and Native code – untyped intermediate lambda code where pattern matching is optimized, bytecode ocamlc compiler and ocamlrun interpreter, and native code ocamlopt code generator, and debugging and profiling native code.

The online HTML version of the book is available under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.

Read the book


2. Unix system programming in OCaml by Xavier Leroy and Didier Rémy

Unix system programming in OCaml

Unix system programming in OCaml is an introductory course on Unix system programming, with an emphasis on communications between processes. The main novelty of this work is the use of the OCaml language, a dialect of the ML language, instead of the C language that is customary in systems programming. This gives an unusual perspective on systems programming and on the ML language.

This document describes only the programmatic interface to the Unix system. It presents neither its implementation, neither its internal architecture.

Chapters cover:

  • Generalities – modules Sys and Unix, interface with the calling program, error handling, and library functions.
  • Files – including opening a file, reading and writing, positioning, locks on files, complete examples: file copy, recursive copy of files, and Tape ARchive.
  • Processes – creation of processes, awaiting the termination of a process, launching a program, complete examples: the command leave, a mini-shell.
  • Signals – includes how to use signals, using signals, how to mask signals, signals and system calls, problems with signals.
  • Classical inter-process communication: pipes – pipes, named pipes, descriptor redirectors, input/out multiplexing, complete examples: parallel sieve of Eratosthenes, composing N commands.
  • Modern communication: sockets – sockets, socket creation, addresses, disconnecting sockets, establishing a service, tuning sockets, high-level primitives, complete examples: the universal client, the universal server, HTTP requests.
  • Threads – creation and termination of threads, waiting, synchronization among threads: locks, conditions, event-based synchronous.

Unix System Programming in OCaml is distributed under a Creative Commons by-nc-sa license.

Read the book


3. How to Think Like a (Functional) Programmer by Allen Downey and Nicholas Monje

How to Think Like a (Functional) Programmer

How to Think Like a Computer Scientist is an introductory programming textbook based on the OCaml language which teaches the reader to think like a computer scientist.

It’s a modified version of Think Python by Allen Downey.

The book is intended for newcomers to programming and also those who know some programming but want to learn programming in the function-oriented paradigm, or those who simply want to learn OCaml.

Chapters cover:

  • The way of the program.
  • Variables and Expressions – includes values and types, variables, expressions, string operations, and debugging.
  • Functions – includes function calls, math functions, composition, adding new functions, and more.
  • Program Flow – includes coverage of Boolean expressions, logical operators, chained conditionals.
  • Recursive Functions – recursion, infinite recursion, mutually recursive functions, tail-end recursion, and debugging.
  • Algorithms – square roots, algorithms, and debugging.
  • Strings – string.length, substrings, string traversal, searching, string comparison, and debugging.
  • Lists – list operations, list iteration, mapping and folding, list sorting, lists and recursion, and debugging.
  • Case Study: Regular Expressions.
  • Putting the O in OCaml, Part 1: Imperative programming.
  • Arrays – making arrays, array operations, array iteration, mapping, and folding, array sorting, and array traversal.
  • Hashtables – includes folding and hashtables, reverse lookup, memos and more.
  • Tuples – includes enumerated types, and aggregate types.
  • Records and Custom Data Structures.
  • Putting the O in OCaml, Part 2: Objects and Classes.
  • Case study: data structure selection.

Permission is granted to copy, distribute, and/or modify this book under the terms of the GNU Free Documentation License, Version 1.1 or any later version.

Read the book


Next page: Page 2 – Using, Understanding, and Unraveling The OCaml Language and more books

Pages in this article:
Page 1 – Real World OCaml and more books
Page 2 – Using, Understanding, and Unraveling The OCaml Language and more books


All books in this series:

Free Programming Books
AdaALGOL-like programming language, extended from Pascal and other languages
AgdaDependently typed functional language based on intuitionistic Type Theory
ArduinoInexpensive, flexible, open source microcontroller platform
AssemblyAs close to writing machine code without writing in pure hexadecimal
AwkVersatile language designed for pattern scanning and processing language
BashShell and command language; popular both as a shell and a scripting language
BASICBeginner’s All-purpose Symbolic Instruction Code
CGeneral-purpose, procedural, portable, high-level language
C++General-purpose, portable, free-form, multi-paradigm language
C#Combines the power and flexibility of C++ with the simplicity of Visual Basic
ClojureDialect of the Lisp programming language
ClojureScriptCompiler for Clojure that targets JavaScript
COBOLCommon Business-Oriented Language
CoffeeScriptTranscompiles into JavaScript inspired by Ruby, Python and Haskell
CoqDependently typed language similar to Agda, Idris, F* and others
CrystalGeneral-purpose, concurrent, multi-paradigm, object-oriented language
CSSCSS (Cascading Style Sheets) specifies a web page’s appearance
DGeneral-purpose systems programming language with a C-like syntax
DartClient-optimized language for fast apps on multiple platforms
DylanMulti-paradigm language supporting functional and object-oriented coding
ECMAScriptBest known as the language embedded in web browsers
EiffelObject-oriented language designed by Bertrand Meyer
ElixirRelatively new functional language running on the Erlang virtual machine
ErlangGeneral-purpose, concurrent, declarative, functional language
F#Uses functional, imperative, and object-oriented programming methods
FactorDynamic stack-based programming language
ForthImperative stack-based programming language
FortranThe first high-level language, using the first compiler
GoCompiled, statically typed programming language
GroovyPowerful, optionally typed and dynamic language
HaskellStandardized, general-purpose, polymorphically, statically typed language
HTMLHyperText Markup Language
IconWide variety of features for processing and presenting symbolic data
JArray programming language based primarily on APL
JavaGeneral-purpose, concurrent, class-based, object-oriented, high-level language
JavaScriptInterpreted, prototype-based, scripting language
JuliaHigh-level, high-performance language for technical computing
KotlinMore modern version of Java
LabVIEWDesigned to enable domain experts to build power systems quickly
LaTeXProfessional document preparation system and document markup language
LispUnique features - excellent to study programming constructs
LogoDialect of Lisp that features interactivity, modularity, extensibility
LuaDesigned as an embeddable scripting language
MarkdownPlain text formatting syntax designed to be easy-to-read and easy-to-write
Objective-CObject-oriented language that adds Smalltalk-style messaging to C
OCamlThe main implementation of the Caml language
PascalImperative and procedural language designed in the late 1960s
PerlHigh-level, general-purpose, interpreted, scripting, dynamic language
PHPPHP has been at the helm of the web for many years
PostScriptInterpreted, stack-based and Turing complete language
PrologA general purpose, declarative, logic programming language
PureScriptSmall strongly, statically typed language compiling to JavaScript
PythonGeneral-purpose, structured, powerful language
QMLHierarchical declarative language for user interface layout - JSON-like syntax
RDe facto standard among statisticians and data analysts
RacketGeneral-purpose, object-oriented, multi-paradigm, functional language
RakuMember of the Perl family of programming languages
RubyGeneral purpose, scripting, structured, flexible, fully object-oriented language
RustIdeal for systems, embedded, and other performance critical code
ScalaModern, object-functional, multi-paradigm, Java-based language
SchemeA general-purpose, functional language descended from Lisp and Algol
ScratchVisual programming language designed for 8-16 year-old children
SQLAccess and manipulate data held in a relational database management system
Standard MLGeneral-purpose functional language characterized as "Lisp with types"
SwiftPowerful and intuitive general-purpose programming language
TclDynamic language based on concepts of Lisp, C, and Unix shells
TeXMarkup and programming language - create professional quality typeset text
TypeScriptStrict syntactical superset of JavaScript adding optional static typing
ValaObject-oriented language, syntactically similar to C#
VHDLHardware description language used in electronic design automation
VimLPowerful scripting language of the Vim editor
XMLRules for defining semantic tags describing structure ad meaning
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Please read our Comment FAQ before posting a comment.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments