💻 Programming

OCaml

Objective Caml

An ML-family language supporting functional, imperative, and object-oriented programming

📖 Detailed Explanation

OCaml (Objective Caml) is a general-purpose programming language of the ML (Meta Language) family, and a multi-paradigm language that supports functional, imperative, and object-oriented paradigms. It provides a powerful static type system and automatic memory management, while achieving performance comparable to C/C++ through native code compilation.

OCaml was developed at the French National Institute for Research in Digital Science and Technology (INRIA). In 1996, a team led by Xavier Leroy released OCaml by adding object-oriented features to Caml Light. Its roots go back to ML, developed by Robin Milner in 1973, and it has evolved on the basis of more than 50 years of academic research.

The key features of OCaml are Hindley-Milner type inference, algebraic data types (ADTs), and pattern matching. The compiler infers types automatically even when the programmer does not specify them, and pattern matching makes it possible to handle complex data structures concisely and safely. It catches most bugs at compile time, to the point that there is a saying, "if it compiles, it works."

In practice, OCaml is actively used in the financial sector and at large technology companies. Jane Street has built its entire trading infrastructure in OCaml and processes trades worth trillions of won per day, and Meta (Facebook) developed the Hack language compiler and the Flow type checker in OCaml. In addition, early versions of the Rust compiler, Docker's container technology (MirageOS), and the formal verification tool Coq were also written in OCaml.

💻 Code Example

This is an example showing OCaml's basic syntax and pattern matching.

(* 기본 함수 정의 - 타입 추론 *)
let square x = x * x
let add x y = x + y

(* 재귀 함수 - rec 키워드 필요 *)
let rec factorial n =
  if n <= 1 then 1
  else n * factorial (n - 1)

(* 대수적 데이터 타입 정의 *)
type shape =
  | Circle of float              (* 반지름 *)
  | Rectangle of float * float   (* 너비 * 높이 *)
  | Triangle of float * float    (* 밑변 * 높이 *)

(* 패턴 매칭으로 면적 계산 *)
let area shape =
  match shape with
  | Circle r -> Float.pi *. r *. r
  | Rectangle (w, h) -> w *. h
  | Triangle (b, h) -> 0.5 *. b *. h

(* Option 타입으로 안전한 나눗셈 *)
let safe_divide x y =
  if y = 0 then None
  else Some (x / y)

(* 리스트 처리 - 패턴 매칭 활용 *)
let rec sum_list = function
  | [] -> 0
  | head :: tail -> head + sum_list tail

(* 고차 함수 사용 *)
let numbers = [1; 2; 3; 4; 5]
let doubled = List.map (fun x -> x * 2) numbers
let total = List.fold_left (+) 0 numbers

(* 파이프 연산자로 가독성 향상 *)
let result =
  numbers
  |> List.filter (fun x -> x mod 2 = 0)
  |> List.map (fun x -> x * x)
  |> List.fold_left (+) 0

(* 레코드 타입 *)
type person = {
  name: string;
  age: int;
  email: string option;
}

let alice = { name = "Alice"; age = 30; email = Some "alice@example.com" }

(* 모듈 시스템 *)
module Stack = struct
  type 'a t = 'a list

  let empty = []
  let push x stack = x :: stack
  let pop = function
    | [] -> None
    | x :: rest -> Some (x, rest)
end

🗣️ Say It Like This in Practice

💬 In a Technical Discussion
"OCaml's type system fundamentally blocks runtime errors such as null pointer exceptions at compile time. Because null is handled explicitly with the Option type, 'if it compiles, it works' is really true."
💬 In an Interview
"OCaml's pattern matching is not a simple switch statement; the compiler warns you about missing cases. Combined with algebraic data types, even complex business logic can be expressed without bugs."
💬 In a Team Meeting
"The reason we use OCaml for financial systems like Jane Street is type safety and performance. Thanks to type inference, the compiler catches all type errors even without type declarations, and native compilation makes it fast too."
💬 In a Code Review - Pattern Matching
"You're using a wildcard (_) in this match statement, but if a variant is added later, you won't get a compiler warning. If possible, handle all cases explicitly. Also, using Option.get on this Option type throws an exception when the value is None. It's safer to give a default value with Option.value ~default or handle it with match."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

📈
Learning curve: If you are not familiar with the functional programming paradigm, the initial learning can be difficult. Concepts such as monads, functors, and type classes in particular require time to understand. We recommend starting with a practice-oriented textbook such as "Real World OCaml."
📦
Ecosystem size: The library ecosystem is smaller than those of JavaScript or Python. The opam package manager has about 4,000 packages, but that is limited compared to npm's 2 million. If a particular library is missing, you may have to implement it yourself or use the C FFI.
⚡
Parallelism limitations: Earlier versions of OCaml had limitations in multicore parallel processing because of the GIL (Global Interpreter Lock). Fortunately, since OCaml 5.0 (2022), multicore is supported natively, and asynchronous programming through Effect Handlers has also become possible.
👥
Hiring: The pool of OCaml developers is relatively small, so hiring can be difficult. However, developers who choose OCaml are generally highly skilled and have a deep understanding of functional programming, so team productivity tends to be high.

🔗 Related Terms

📚 Learn More