OCaml Programming Language Cheatsheet

If you’re diving into the world of functional programming or exploring languages with strong static typing, OCaml might be the language for you. OCaml, short for Objective Caml, is a powerful and expressive programming language known for its emphasis on functional programming and strong type inference. Whether you’re a beginner or an experienced developer, having a cheatsheet can be incredibly helpful for quick reference. In this blog post, we’ll provide a concise OCaml programming language cheatsheet to aid you in your coding endeavors.

1. Hello World:

(* hello.ml *)
print_string "Hello, World!\n";;

To compile and run:

ocamlc -o hello hello.ml

2. Variables and Types:

let x = 42;;           (* Integer *)
let name = "OCaml";;   (* String *)
let pi = 3.14;;        (* Float *)
let is_true = true;;    (* Boolean *)

3. Functions:

let add x y = x + y;;              (* Function with type inference *)
let multiply = fun x y -> x * y;;  (* Anonymous function *)

4. Pattern Matching:

let rec factorial n =
  match n with
  | 0 -> 1
  | _ -> n * factorial (n - 1);;

5. Lists:

let numbers = [1; 2; 3; 4; 5];;   (* List *)
let combined = [0] @ numbers;;     (* List concatenation *)
let head = List.hd numbers;;       (* First element *)
let tail = List.tl numbers;;       (* Rest of the list *)

6. Tuples:

let point = (3, 4);;               (* Tuple *)
let x, y = point;;                 (* Pattern matching on tuple *)

7. Records:

type person = {name: string; age: int};;   (* Define a record type *)
let alice = {name="Alice"; age=30};;      (* Create a record instance *)
let alice_age = alice.age;;                (* Access field of a record *)

8. Option Type:

let divide x y =
  if y = 0 then None
  else Some (x / y);;

9. Modules:

module Math = struct
  let add x y = x + y
  let multiply x y = x * y

let sum = Math.add 3 4;;

10. Exception Handling:

exception NegativeValue of string;;

let safe_sqrt x =
  if x < 0. then raise (NegativeValue "Cannot take square root of a negative number")
  else sqrt x;;

11. File I/O:

let read_file filename =
  let ic = open_in filename in
    let content = input_line ic in
    close_in ic;
  with e ->
    close_in_noerr ic;
    raise e;;

12. Recursive Functions:

let rec factorial n =
  if n = 0 then 1
  else n * factorial (n - 1);;

This OCaml cheatsheet covers some of the fundamental aspects of the language, helping you get started with OCaml programming. As you explore the language further, you’ll discover its rich set of features for functional programming, type safety, and efficient pattern matching. Keep this cheatsheet handy as you embark on your OCaml programming journey, and don’t hesitate to delve deeper into the language’s documentation and community resources for more advanced topics and techniques.


What is OCaml known for?

OCaml is renowned for its strong type inference, emphasis on functional programming, and efficient pattern matching capabilities.

How do I handle errors in OCaml?

Error handling in OCaml is often done using the option type for functions that may fail or through exceptions for exceptional cases.

Can OCaml be used for web development?

Yes, OCaml has web development frameworks like Ocsigen that enable building robust and scalable web applications using functional programming principles.

How does OCaml handle mutability?

OCaml emphasizes immutability, but mutable data structures like arrays and references exist. However, the language encourages immutable programming for better safety.

Is OCaml suitable for beginners?

While OCaml may have a steeper learning curve for beginners, its strong type system and functional programming principles provide a solid foundation for building robust software.