EMZETT.
Login

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

Kapitel 8 von 8 im Kurs OCaml. Mit Fortschritt, Quiz und Zertifikat auf der Lernseite.

Syntax im Überblick

KonzeptOCaml
Bindunglet x = 1 in ...
Funktionlet f x y = x + y
Anonymfun x -> x * 2
Rekursionlet rec f n = ...
Bedingungif c then a else b
Mustermatch x with | A -> ... | B -> ...
Liste[1; 2; 3], x :: rest, a @ b
Tupel(1, "a")
Record{ name = "x"; alter = 3 }
Variantetype t = A | B of int
OptionSome x, None
Referenzref 0, !r, r := 1
Array[| 1; 2 |], a.(0)
Modulmodule 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      2

Typische Fehler

let () = print_int 3.5

Fehlermeldung:

This expression has type float but an expression was expected of type
         int
let f x = x + 1
let () = print_int (f "a")

Fehlermeldung:

This expression has type string but an expression was expected of type
         int

Achtung

Ein ; direkt vor in oder done ist 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, mutable und 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

Weiter im Kurs

Zurück: Dateien, Werkzeuge und Ökosystem

Alle Kapitel: OCaml im Überblick