01
Primeros pasos
Hola Mundo
Los programas OCaml empiezan con let () = ...
ocaml
let () = print_endline "Hello, World!"Declaraciones let
Las declaraciones let son inmutables por defecto.
ocaml
let x = 10
let y = 20
let () = Printf.printf "%d\n" (x + y)Funciones
Las funciones se currifican automáticamente.
ocaml
let add a b = a + b
let () = print_int (add 3 4)Pipe
|> es el 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
Registros
Los registros son tipos producto con campos con nombre.
ocaml
type person = { name: string; age: int }
let p = { name = "Alice"; age = 30 }
let () = print_string p.nameVariantes
Las variantes son tipos suma; haz pattern matching con function.
ocaml
type shape =
| Circle of float
| Rectangle of float * float
let area = function
| Circle r -> 3.14 *. r *. r
| Rectangle (w, h) -> w *. hOpciones
El tipo Option para seguridad frente a valores nulos.
ocaml
let safe_div a b =
if b = 0 then None else Some (a / b)03
Colecciones
Listas
El módulo List tiene las operaciones estándar de la programación 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
Los arrays son mutables; se indexan con .()
ocaml
let arr = [|1; 2; 3|]
let () = arr.(0) <- 10Was this helpful?