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 (+) 002
型
レコード
レコードは名前付きの積型です。
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 *. hOptions
null 安全のために 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) <- 10Was this helpful?