01
Erste Schritte
Hello World
OCaml-Programme beginnen mit let () = ...
ocaml
let () = print_endline "Hello, World!"Let-Bindings
let-Bindings sind standardmäßig unveränderlich.
ocaml
let x = 10
let y = 20
let () = Printf.printf "%d\n" (x + y)Funktionen
Funktionen werden automatisch curried.
ocaml
let add a b = a + b
let () = print_int (add 3 4)Pipe
|> ist der Pipe-Operator.
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
Typen
Records
Records sind benannte Produkttypen.
ocaml
type person = { name: string; age: int }
let p = { name = "Alice"; age = 30 }
let () = print_string p.nameVariants
Variants sind Summentypen; Pattern-Matching mit 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
Der Option-Typ für Null-Sicherheit.
ocaml
let safe_div a b =
if b = 0 then None else Some (a / b)03
Collections
Listen
Das List-Modul bietet die Standard-FP-Operationen.
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 sind veränderbar; Indexierung mit .()
ocaml
let arr = [|1; 2; 3|]
let () = arr.(0) <- 10Was this helpful?