Syntax im Überblick
| Konzept | OCaml |
|---|---|
| Bindung | let x = 1 in ... |
| Funktion | let f x y = x + y |
| Anonym | fun x -> x * 2 |
| Rekursion | let rec f n = ... |
| Bedingung | if c then a else b |
| Muster | match x with | A -> ... | B -> ... |
| Liste | [1; 2; 3], x :: rest, a @ b |
| Tupel | (1, "a") |
| Record | { name = "x"; alter = 3 } |
| Variante | type t = A | B of int |
| Option | Some x, None |
| Referenz | ref 0, !r, r := 1 |
| Array | [| 1; 2 |], a.(0) |
| Modul | module M = struct ... end |
Wichtige Funktionen
let () =
let l = [3; 1; 2] in
let zeile name wert = Printf.printf "%-10s %s\n" name wert in
let s l = "[" ^ String.concat ";" (List.map string_of_int l) ^ "]" in
zeile "map" (s (List.map succ l));
zeile "filter" (s (List.filter (fun x -> x > 1) l));
zeile "sort" (s (List.sort compare l));
zeile "rev" (s (List.rev l));
zeile "fold" (string_of_int (List.fold_left (+) 0 l));
zeile "length" (string_of_int (List.length l));
zeile "nth" (string_of_int (List.nth l 1));
zeile "mem" (string_of_bool (List.mem 2 l));
zeile "assoc" (string_of_int (List.assoc "b" [("a", 1); ("b", 2)]))map [4;2;3] filter [3;2] sort [1;2;3] rev [2;1;3] fold 6 length 3 nth 1 mem true assoc 2
Typische Fehler
let () = print_int 3.5This expression has type float but an expression was expected of type
intlet f x = x + 1
let () = print_int (f "a")This expression has type string but an expression was expected of type
intWeiterführende Quellen
- ocaml.org: Dokumentation, Tutorials, Paketsuche
- „Real World OCaml“ (kostenlos online)
- „OCaml Programming: Correct + Efficient + Beautiful“ (Cornell)
- discuss.ocaml.org: Community-Forum
Merke
- OCaml: funktional, streng typisiert, schnell, mit Modulsystem
- Unveränderlichkeit ist Standard; Veränderlichkeit mit
ref,mutableund Arrays - Der Compiler prüft Typen und Vollständigkeit von
match
Aufgabe
Setze ein kleines Programm mit dune auf und füge einen Test hinzu.