Kurz: > Achtung: Ein ; direkt vor in oder done ist ein Syntaxfehler. Mit ; trennst du Ausdrücke, ein Ausdruck nach ; muss folgen.
Teil des Kurses OCaml
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)]))Ausgabe:
map [4;2;3]
filter [3;2]
sort [1;2;3]
rev [2;1;3]
fold 6
length 3
nth 1
mem true
assoc 2Typische Fehler
let () = print_int 3.5Fehlermeldung:
This expression has type float but an expression was expected of type
intlet f x = x + 1
let () = print_int (f "a")Fehlermeldung:
This expression has type string but an expression was expected of type
intAchtung
Ein
;direkt vorinoderdoneist ein Syntaxfehler. Mit;trennst du Ausdrücke, ein Ausdruck nach;muss folgen.
Weiterfü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
Übungsaufgabe
Setze ein kleines Programm mit dune auf und füge einen Test hinzu.
Quiz zur Selbstkontrolle
Aus welcher Sprachfamilie stammt OCaml?
- ML (richtig)
- C
- Lisp
- Smalltalk
Was ist der Vorteil der Typinferenz?
- Typen werden meist automatisch erkannt, ohne Annotationen (richtig)
- Es gibt keine Typen
- Der Code ist langsamer
- Typen sind optional zur Laufzeit
Wie hängt man ein Element vorn an eine Liste an?
- x :: liste (richtig)
- liste.add(x)
- liste @ x
- push x
Weiter im Kurs
Zurück: Dateien, Werkzeuge und Ökosystem
Alle Kapitel: OCaml im Überblick