Ocaml Cheat Sheet



  1. Ocaml Cheat Sheet 2020
  2. Ocaml Cheat Sheet Printable
  3. Ocaml Cheat Sheet 2019

OCaml Documentations as one-pagers, easy to keep useful commands in mind - OCamlPro/ocaml-cheat-sheets. ◆ Website ◆ (The listing sheet, as PDF, can be found here, or as a single column portrait, while below is an unruly html rendition. This reference sheet is built from a CheatSheets with Org-mode system. A course on functional programming at Cornell University.

[◆ Website ◆](https://alhassy.github.io/OCamlCheatSheet/)

The listing sheet, as PDF, can be foundhere,or as a single column portrait,while below is an unruly html rendition.

This reference sheet is built from aCheatSheets with Org-modesystem.

  1. Emacs Setup:HTML:

OCaml is a strict language;it is strongly typed where types are inferred.

I may write explicit type annotations below for demonstrationor clarity purposes.

Only when interacting with the top-level interpreter,commands must be terminated by ;;.OCaml uses ; as an expression separator —not a terminator!

My Emacs setup for OCaml can be found on this CheatSheet’s repo.

First, let’s get [Meta]OCaml.

Let’s set this up for Emacs.

Let’s obtain ocp-indent —OCaml’s indentation tool that indents the same even ifco-workers use a different editor— and merlin which provides interactive feedbackincluding context-aware completion and jumping to definitions.

Now entering, say, List. brings a pop-up completion menu for thecontents of the list module.

—In org-src blocks, you need to enter the ocaml mode, via C-c '.

Operations on floats have a ‘.’ suffix.

A function is declared with the let keyword—variables are functions of zero arguments.Function & varaible names must begin with a lowercase letter, and may use _ or '.

  • They cannot begin with capital letters or numbers, or contain dashes!
  • Functions are like variables, but with arguments, so the same syntax applies.
(* A curried function *) let f x y = x + y (* Function application *) let result = f 10 (2 * 6) (* Partial application *) let g x = f x 2 (* We can re-bind variables *) let x = 123 let x = string_of_int xRecursive functions are marked with the `rec` keyword. let rec fact n = if n = 0 then 1 else n * fact (n - 1)

Ocaml Cheat Sheet 2020

Here’s an example of a higher-order function & multiple local functions& an infix operator & an anonymous function & the main method isparametricly polymorphic.

Ocaml Cheat Sheet

Inequality is expressed with <>.

OCaml strings are not arrays, or lists, of characters as in C or Haskell.

Records: Products with named, rather than positional, components.

Variant types: A unified way to combine different types into a single type;each case is distinuighed by a capitalised tag.

The tags allow us to extract components of a variant valueas well as to case against values by inspecting their tags.This is pattern matching.

Note that we can give a pattern a name; above we mentioned p,but did not use it.

  • Repeated & non-exhaustive patterns trigger a warning; e.g., remove the default case above.

  • You can pattern match on arrays too; e.g.,[| x ; y ; z|] -> y.

The above mechanisms apply to all variants —including tuples, lists, and options.

Tuples: Parentheses are optional, comma is the main operator.

columnbreak

Option: Expressing whether a value is present or not.

We may use begin/end or parentheses to groupexpressions together.

(* Inline *) let x = begin 1 * 2 end + (3 - 2);; (* Parentheses *) ( print_string 'a' ; () (* This is the unit value *) ; 9 );; (* Begin-end block *) begin print_string 'nice'; 'bye'; true; 10 end;;

Remember: Single semicolon ; is for sequencing whereas double ;; is for termination.

OCaml programs don’t have a unique main function as in C, instead the entire fileis evaluated sequentially at startup, which may contain arbitrary expressions not just functional declarations,and so in some sense the full codebase is one big main function.

Zero-indexed Arrays: Indexing with .(i) and update with <-.

What is the type of update, <-? A function that returns the unit type!—see myupdate below.

Operations whose use produces a side-effect return the unit type.This’ akin to the role played by void in C.A function is a sequence of expressions; its return valueis the value of the final expression —all other expressionsare of unit type.

(* type unit = () *) let ex : unit = ();; let myupdate (arr : 'a array) (e : 'a) (i : int) : unit = arr.(i) <- e;; myupdate nums 33 1;; [|12; 33; 3|] = nums;; let my_io () = print_endline 'Hello!' ;; let const x y = my_io(); y; x;; let res = const 1972 12;;

Record fields are immutable by default, but can be declared mutable.

References: Single mutable values; i.e., a record with a single mutable field named contents.

Refs come with a handful of convenience methods; here’s their re-implementation:

Notice that ref Dirt 2 for mac. is overloaded: As a type former and as a function forming values.

columnbreak

OCaml files not only store & manage code, but also correspond to (second-class) ‘modules’,which act as boundaries that divide a program into conceptual units.

  • At its simplest, a module is a collection of definitions that are storedwithin a namespace.

  • Implementation details of a module can be hidden by using aninterface, module type, signature —all are aliases.
    • val declarations specify values in a signature: val ⟪identifier⟫ : ⟪type⟫.
    • A type is abstract if its name is exposed in the interface but its definition is not: type t.
      • It is conventional to use t for the name of such types.
    • Including the type definition in the interface makes the type concrete.
  • E.g., module names are derived, with capitalisation, automatically from file names.An interface for myfile.ml to constrain exposed interface is placed in myfile.mli.

    This is nearly how C header and implementation files work.

  • Modules & signatures can be nested inside other modules.

Modules names always begin with a capital; their contents are accessed withdot notation. Here is the general syntax:

Without constructors type creates aliases, if we want to treat a type in two differentways and have the compiler ensure we don’t mess-up, we produce single-constructor newtypes:

type person = P of string;; type address = A of string;; let jasim : person = P 'jasim';; let home : address = A 'the farm';; (* Type error *) let this : person = home;; (* If needed, we could make coercions *) let person_to_string : person -> string = function P s -> s let address_of_string : string -> address = fun s -> A s

However, if the underlying type were the same, this repetition could be error-prone.Instead, we could use generative modules: Distinct types with the same underlying implementation.Being ‘generative’ is akin to the new keyword in Java: Each use of the BasicImplementation module below makes a new type.

module type EssentiallyString = sig type t val to_string : t -> string val from_string : string -> t val (=) : t -> t -> bool end module BasicImplementaion : EssentiallyString = struct type t = string let to_string x = x let from_string x = x let (=) l r = String.(l = r) end

Note that BasicImplemention is just a namespace where, e.g., t is an alias for string.

Note that we could have placed the definitions of EssentiallyStringand newline BasicImplementaion in-line for the Person and Address moduledeclarations —without syntactic alterations— but that would havedefeated our purpose of avoiding repetition.

Without the type annotation, we could accidentally forget to implementpart of the interface & OCaml would infer a different module type.Use the module type of operator to see what was inferred.

Many equivalent ways to use module contents —the third is for small expressions.

  • Note the dot!

    let qasim = Person.(from_string “jasim”)in (let open Person in qasim = jasim) , Person.(=) qasim jasim , Person.(from_string “jasim” = jasim) (* Rebind module name to a shorter name *) , let module P = Person in P.(qasim = jasim);;

While opening a module [type] affects the environment used to search for identifiers,including a module is a way of adding new identifiers to a module [type] proper—it is a copy-paste of constituents.For example, we could re-organise EssentialyString into a hierarchy:

This allows us to form extensions to modules, akin to C#:To extend, say, the List module with a new function f so thatList.f is valid, we make and open module List = struct let f = ⋯ include List.If we wanted to override an existing f, we put its definition after the include.

The interface would be sig val f : ⋯ include (module type of List) end.

When we have multiple declarations of a type or we have type that is too abstract to beof use, expect to see:Error: This expression has type 𝓉 but an expression was expected of type M.t; instead maybe use M.t with type t = 𝓉, where:

We may now continue our EssentiallyString hierarchy:

Warning!The order of constructor declarations for a concrete type variant must be thesame in the implementation as in the interface, likewise for record fields andfunction arguments.

Functors are, roughly speaking, functions from modules to modules.— There’s no “modules to module types” thing, instead we returna module that contains a module type ;-) —

roomFunctors provide the same abstraction features as functions do but alsoallow the implementation of one module to vary depending on another module.In contrast to functions, functors require explicit type annotation—otherwise how would we know what constituents the input module contains—and their arguments must be enclosed in parentheses.

In a sense, these are parameterised modules —as in Agda— and that is howthey may be treated syntactically in OCaml:

A functor may be applied to any module that satisfies the functor’s input interface:

Modules can contain types & values, but ordinary values can’t contain modules ormodule types. In order to define variables whose value is a module, or a functionthat takes a module as an argument, OCaml provides first-class modules which areordinary values that can be created from and converted back to regular modules.

A first-class module is created by packaging up a module with a signature thatit satisfies by using the module keyword:

Dot notation only works for records and modules, so we access contents of afirst-class module by turning it into an ordinary module with val:

Warning! The parentheses for these module, val keywords are important!

Rule of thumb: Use the forms (module M : T) and (val M : T) always.

We can create ordinary functions which consume and create first-class modules.

columnbreak Apple wallpapers for mac.

Type variables are generally implicit, but we can treat them as abstract typesin a function body yet still not pass them in explicitly at use-sites.

One use is to connect the abstract types of a first-class module with other typeswe’re working with —by using constraint sharing.That is, we ‘unbundle’ the type from ‘inside’ the module to its ‘type’.This is a prime reason to use first-class modules!

Here’s an example where we approximate C#’s default keyword:

Conversely, this allows us to ‘bundle’ up data to form a module!

Quasi-quote expressions with ‘brackets’ .< expr >.to delay their executionand splice quoted items into such an expression with ‘escape’ .~expr.Finally, code can be ‘run’ with Runcode.run expr.

Warning! You must use the metaocaml command rather than the ocaml command.

The traditional ‘staging of the power function’ examplecan be found here —as a Jupyter Notebook.

For more, see A Gentle Introduction to Multi-stage Programming

  • The deprecated !. is replaced with Runcode.run.
  • A Haskell rendition can be found here.

columnbreak

  • Learn x in y minutes, where x = OCaml
  • Try OCaml, online
  • Real World OCaml
  • OCaml meta tutorial —including 99 Problems
  • Unix system programming in OCaml

OCaml-Top is designed for beginners andstudents, and specially tailored for exercises, practicals and simpleprojects

Features

Syntax coloring

Ocaml Cheat Sheet Printable

Automatic, state-of-the-art code indentation

Naturally avoids most beginner's syntactic mistakes

Intuitive code execution

'Run' button runs just what you would expect: the expression under cursor, and what is above if needed

Automatic type display

Put your cursor on the name of a standard library function, and the type shows up in the status bar. Non-intrusive, but here just when you need it.

Fully compatible with Microsoft Windows XP, Vista, 7 and 8, OSX and Linux.
Ocaml Cheat Sheet

Documentation

Installation

On Linux or OSX, we recommend you use the OPAM package manager:

First install opam and some gtk dependancies. For example, with Ubuntu:

Then you need to install OCaml:

Sheet

Avchd mts converter for mac. Finally install ocaml-top

On Microsoft Windows, download and run our binaryinstaller. You will also need a working installation of OCaml itself,for which werecommend theinstaller by Jonathan Protzenko. You need no extra options besides OCamlitself.

Usage

The left pane is the code editor, while the right pane contains the OCaml process that will execute the code.

The in the left margin of the editor is the evaluation mark, showing that the code has been successfully executed up to that point. When pressing the button (or Ctrl e), the expression under the cursor is sent to the OCaml pane, and the answer from OCaml is displayed there. In case of an error, the relevant part of the code in the editor is highlighted.

Since programs are usually written in order, the evaluation mark always progresses from top to bottom, and everything in-between the current mark position and the expression to run will be sent to OCaml first. If you happen to need execution of an expression directly, select it before pressing .

The button runs the whole program. In case you get confused, the button restarts a fresh OCaml, rewinds the evaluation mark, and clears the right pane. And in case you got yourself in a loop, or your program just takes too long, the button can interrupt the current computation.

Keyboard shortcuts

File management
Ctrl nStart with a new (blank) file
Ctrl oLoad a file
Ctrl sSave the current file
Edition
Ctrl cCopy
Ctrl xCut
Ctrl vPaste
Ctrl zUndo
Ctrl Shift zRedo
Execution
Ctrl eExecute the current expression
EscapeStop ongoing execution
General
Ctrl +Zoom in
Ctrl -Zoom out
F4Select font
F5Switch colors
F11Switch fullscreen
Ctrl qQuit

Ocaml Cheat Sheet 2019

Resources

OCaml-Top on GithubLatest sources in the official GIT repository
Version 1.1.2 Download for Linux, OSX and Windows