01
Primeiros Passos
Hello World
Programas OCaml começam com let () = ...
ocaml
let () = print_endline "Hello, World!"Ligações Let
Ligações let são imutáveis por padrão.
ocaml
let x = 10
let y = 20
let () = Printf.printf "%d\n" (x + y)Funções
Funções são curried automaticamente.
ocaml
let add a b = a + b
let () = print_int (add 3 4)Pipe
|> é o operador pipe.
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
Tipos
Records
Records são tipos produto nomeados.
ocaml
type person = { name: string; age: int }
let p = { name = "Alice"; age = 30 }
let () = print_string p.nameVariants
Variants são tipos soma; faça pattern matching com 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
Tipo Option para segurança contra null.
ocaml
let safe_div a b =
if b = 0 then None else Some (a / b)03
Coleções
Listas
O módulo List tem as operações padrão de programação funcional.
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 são mutáveis; indexados com .()
ocaml
let arr = [|1; 2; 3|]
let () = arr.(0) <- 10Was this helpful?