100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

OCaml Cheat Sheet

OCaml Cheat Sheet

Practical OCaml syntax covering let bindings, pattern matching, lists, and algebraic data types like records, variants, and options.

2 PagesIntermediateMar 22, 2026

Bindings & Functions

let bindings and function definitions with type inference.

ocaml
let x = 10let square x = x * xlet add a b = a + blet () =  print_endline "Hello, World!";  Printf.printf "Square: %d\n" (square 5)(* explicit type annotations *)let divide (a : float) (b : float) : float = a /. b

Pattern Matching

match expressions and guards.

ocaml
let describe n =  match n with  | 0 -> "zero"  | n when n > 0 -> "positive"  | _ -> "negative"let rec length = function  | [] -> 0  | _ :: tail -> 1 + length tail

Lists & Common Functions

Building and transforming immutable lists.

  • [1; 2; 3]- list literal syntax, elements separated by semicolons
  • 1 :: [2; 3]- cons operator, prepends an element
  • lst1 @ lst2- concatenates two lists
  • List.map f lst- applies f to each element, returns a new list
  • List.filter p lst- keeps elements where predicate p is true
  • List.fold_left f acc lst- reduces the list to a single value
  • List.length lst- number of elements in the list
  • List.iter f lst- applies f to each element for side effects only

Records, Variants & Options

OCaml's algebraic data types.

ocaml
type point = { x : float; y : float }let p = { x = 1.0; y = 2.0 }type shape =  | Circle of float  | Rectangle of float * floatlet area = function  | Circle r -> 3.14159 *. r *. r  | Rectangle (w, h) -> w *. hlet safe_div a b =  if b = 0 then None else Some (a / b)match safe_div 10 2 with| Some v -> Printf.printf "%d\n" v| None -> print_endline "division by zero"
Pro Tip

Let the type inferencer do the work — annotate only function signatures for public modules (in the .mli file), not every local let binding; over-annotating makes refactors noisier without adding safety.

Was this cheat sheet helpful?

Explore Topics

#OCaml#OCamlCheatSheet#Programming#Intermediate#BindingsFunctions#PatternMatching#ListsCommonFunctions#RecordsVariantsOptions#DataStructures#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Share this Cheat Sheet