01
Getting Started
Hello World
OCaml programs start with let () = ...
ocaml
let () = print_endline "Hello, World!"Let Bindings
let bindings are immutable by default.
ocaml
let x = 10
let y = 20
let () = Printf.printf "%d\n" (x + y)Functions
Functions are curried automatically.
ocaml
let add a b = a + b
let () = print_int (add 3 4)Pipe
|> is the pipe operator.
ocaml
let result =
[1; 2; 3; 4; 5]
|> List.filter (fun x -> x mod 2 = 0)
|> List.map (fun x -> x * 2)
|> List.fold_left (+) 002
Types
Records
Records are named product types.
ocaml
type person = { name: string; age: int }
let p = { name = "Alice"; age = 30 }
let () = print_string p.nameVariants
Variants are sum types; pattern match with function.
ocaml
type shape =
| Circle of float
| Rectangle of float * float
let area = function
| Circle r -> 3.14 *. r *. r
| Rectangle (w, h) -> w *. hOptions
Option type for null safety.
ocaml
let safe_div a b =
if b = 0 then None else Some (a / b)03
Collections
Lists
List module has standard FP operations.
ocaml
let lst = [1; 2; 3; 4; 5]
let doubled = List.map (fun x -> x * 2) lst
let evens = List.filter (fun x -> x mod 2 = 0) lst
let sum = List.fold_left (+) 0 lstArrays
Arrays are mutable; indexed with .()
ocaml
let arr = [|1; 2; 3|]
let () = arr.(0) <- 10Was this helpful?