Skip to content

OCaml 치트시트

명령형 및 객체지향 기능을 갖춘 함수형 우선 언어로, 강력한 타입 추론을 제공합니다.

01

시작하기

Hello World

OCaml 프로그램은 let () = ...로 시작합니다.

ocaml
let () = print_endline "Hello, World!"

let 바인딩

let 바인딩은 기본적으로 불변입니다.

ocaml
let x = 10
let y = 20
let () = Printf.printf "%d\n" (x + y)

함수

함수는 자동으로 커링됩니다.

ocaml
let add a b = a + b
let () = print_int (add 3 4)

파이프

|>는 파이프 연산자입니다.

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 (+) 0
02

타입

레코드

레코드는 이름이 붙은 곱 타입입니다.

ocaml
type person = { name: string; age: int }
let p = { name = "Alice"; age = 30 }
let () = print_string p.name

배리언트

배리언트는 합 타입이며, function으로 패턴 매칭합니다.

ocaml
type shape =
  | Circle of float
  | Rectangle of float * float

let area = function
  | Circle r -> 3.14 *. r *. r
  | Rectangle (w, h) -> w *. h

옵션

널 안전성을 위한 Option 타입입니다.

ocaml
let safe_div a b =
  if b = 0 then None else Some (a / b)
03

컬렉션

리스트

List 모듈에 표준 함수형 연산이 있습니다.

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 lst

배열

배열은 변경 가능하며, .()로 인덱싱합니다.

ocaml
let arr = [|1; 2; 3|]
let () = arr.(0) <- 10

Was this helpful?