OCaml(Objective Caml)은 강력한 타입 추론, 패턴 매칭, 함수형+객체지향+명령형 멀티패러다임을 지원하는 언어다. Jane Street의 금융 시스템, Facebook의 Hack, Flow 컴파일러가 OCaml로 작성됐다.
핵심 특징
ocaml
(* 타입 추론: 명시적 타입 선언 불필요 *)
let add x y = x + y (* int -> int -> int 자동 추론 *)
let greeting name = "Hello, " ^ name (* string -> string *)
(* 패턴 매칭 *)
let describe n =
match n with
| 0 -> "zero"
| 1 | 2 -> "small"
| n when n < 0 -> "negative"
| _ -> "large"
(* 대수적 데이터 타입 (ADT) *)
type shape =
| Circle of float
| Rectangle of float * float
| Triangle of float * float * float
let area = function
| Circle r -> Float.pi *. r *. r
| Rectangle (w, h) -> w *. h
| Triangle (a, b, c) ->
let s = (a +. b +. c) /. 2.0 in
sqrt (s *. (s-.a) *. (s-.b) *. (s-.c))
모듈 시스템
ocaml
(* 모듈 정의 *)
module Stack : sig
type 'a t
val empty : 'a t
val push : 'a -> 'a t -> 'a t
val pop : 'a t -> ('a * 'a t) option
end = struct
type 'a t = 'a list
let empty = []
let push x s = x :: s
let pop = function [] -> None | x::s -> Some (x, s)
end
(* 펑터 (Functor): 모듈을 받아 모듈 반환 *)
module MakeSet (Ord : Set.OrderedType) = struct
include Set.Make(Ord)
end
module IntSet = MakeSet(Int)
let s = IntSet.(empty |> add 1 |> add 2 |> add 3)
옵션 타입과 오류 처리
ocaml
(* Option: null 안전 *)
let safe_div a b =
if b = 0 then None
else Some (a / b)
(* Result: 오류 전파 *)
let parse_int s =
match int_of_string_opt s with
| Some n -> Ok n
| None -> Error ("Not a number: " ^ s)
(* let* 구문으로 모나딕 체이닝 *)
let compute s1 s2 =
let* n1 = parse_int s1 in
let* n2 = parse_int s2 in
Ok (n1 + n2)
관련 문서