Funktional, statisch typisiert und schnell
Ausführen: Datei hallo.ml speichern und mit ocaml hallo.ml ausführen (OCaml von ocaml.org, Paketmanager opam).
let bindet unveränderliche Werte, let ... in begrenzt sie lokal+ - * / für int, +. -. *. /. für float; keine automatische Umwandlunglet () = ... ist der Startpunktocaml hallo.ml # als Skript starten
ocamlfind ocamlopt -package str hallo.ml -o hallo # nativ übersetzen
dune init project demo # Projekt mit dem Build-System dune
dune build && dune exec demo
utop # komfortable interaktive Konsole
opam install <paket> # Paketmanagerlet f x y = ...; mehrere Argumente werden curryt, partielle Anwendung ist normalif ist ein Ausdruck; Schleifen sind meist Rekursion (let rec)for, while, ref (!, :=) für imperativen Stilmatch ... with und function für Pattern Matchinglet quadrat x = x * x
let addiere a b = a + b
let begruesse name = "Hallo, " ^ name ^ "!"
let () =
Printf.printf "%d %d\n" (quadrat 7) (addiere 3 4);
print_endline (begruesse "Mia");
(* partielle Anwendung *)
let plus10 = addiere 10 in
Printf.printf "%d\n" (plus10 5);
(* anonyme Funktionen *)
let verdopple = fun x -> x * 2 in
Printf.printf "%d\n" (verdopple 21);
(* Funktionen als Argumente *)
let wende_zweimal f x = f (f x) in
Printf.printf "%d\n" (wende_zweimal (fun n -> n + 3) 10):: (voranstellen), @ (verketten), List.map/filter/fold_left[] und kopf :: restmutable optional)option (Some/None) ersetzt nulllet () =
let z = [5; 3; 9; 1; 7] in
let zeige l = print_endline ("[" ^ String.concat "; " (List.map string_of_int l) ^ "]") in
zeige z;
zeige (0 :: z);
zeige (z @ [8; 9]);
zeige (List.rev z);
zeige (List.sort compare z);
zeige (List.map (fun x -> x * 2) z);
zeige (List.filter (fun x -> x > 4) z);
Printf.printf "%d %d\n" (List.length z) (List.hd z);
Printf.printf "%d\n" (List.fold_left (+) 0 z);
Printf.printf "%b %b\n" (List.mem 9 z) (List.exists (fun x -> x > 8) z);
Printf.printf "%b\n" (List.for_all (fun x -> x > 0) z);
zeige (List.init 5 (fun i -> i * i));
zeige (List.concat [[1; 2]; [3]; [4; 5]]);
List.iteri (fun i x -> Printf.printf "%d:%d " i x) [10; 20; 30];
print_newline ();
let (gerade, ungerade) = List.partition (fun x -> x mod 2 = 0) [1; 2; 3; 4; 5; 6] in
zeige gerade; zeige ungerade;
let paare = List.combine [1; 2; 3] ["a"; "b"; "c"] in
List.iter (fun (n, s) -> Printf.printf "%d%s " n s) paare;
print_newline ()type t = A | B of int definiert Varianten; match wird vollständig geprüft'a) Typen modellieren Ausdrücke und Bäumeresult (Ok/Error) für erwartbare Fehler, exception für Ausnahmenas, when und verschachtelte Muster machen match mächtigtype farbe = Rot | Gruen | Blau
type form =
| Kreis of float
| Rechteck of float * float
| Dreieck of float * float * float
let farbname = function
| Rot -> "rot"
| Gruen -> "grün"
| Blau -> "blau"
let flaeche = function
| Kreis r -> 3.14159 *. r *. r
| Rechteck (b, h) -> b *. h
| Dreieck (a, b, c) ->
let s = (a +. b +. c) /. 2.0 in
sqrt (s *. (s -. a) *. (s -. b) *. (s -. c))
let () =
print_endline (farbname Gruen);
List.iter (fun f -> Printf.printf "%.2f\n" (flaeche f))
[Kreis 1.0; Rechteck (2.0, 3.0); Dreieck (3.0, 4.0, 5.0)]String, List, Array, Hashtbl, Map und Set sind Standardmodulemodule/sig kapseln Implementierungen hinter Schnittstellen|> macht Datenflüsse lesbarlet () =
let s = "Hallo OCaml" in
Printf.printf "%d %s %s\n" (String.length s) (String.uppercase_ascii s) (String.lowercase_ascii s);
Printf.printf "%c %s\n" s.[0] (String.sub s 6 5);
Printf.printf "%b %b\n" (String.contains s 'O') (String.starts_with ~prefix:"Hal" s);
Printf.printf "%s\n" (String.concat "-" ["a"; "b"; "c"]);
List.iter print_endline (String.split_on_char ' ' s);
Printf.printf "[%s]\n" (String.trim " x ");
Printf.printf "%s\n" (String.map (fun c -> if c = 'a' then '4' else c) s);
Printf.printf "%d\n" (String.index s 'O');
print_endline (String.make 3 '*');
String.iter (fun c -> Printf.printf "%d " (Char.code c)) "AB";
print_newline ();
Printf.printf "%s %s\n" (string_of_int 42) (string_of_float 2.5);
Printf.printf "%d %.1f\n" (int_of_string "17") (float_of_string "3.5");
Printf.printf "%5d|%-5d|%05d|%x|%e\n" 42 42 42 255 12345.678fold_left/fold_right sind die Grundlage vieler ListenoperationenSeq und lazy verzögern Berechnungen A ``) und GADTs bieten feinere Typenlet () =
let l = [3; 1; 4; 1; 5; 9; 2; 6] in
let summe = List.fold_left (+) 0 l in
let produkt = List.fold_left ( * ) 1 l in
let maximum = List.fold_left max min_int l in
Printf.printf "%d %d %d\n" summe produkt maximum;
(* eigene fold_right: baut die Liste von rechts auf *)
let kopie = List.fold_right (fun x acc -> x :: acc) l [] in
Printf.printf "%b\n" (kopie = l);
let haeufigkeit =
List.fold_left (fun acc x ->
let n = try List.assoc x acc with Not_found -> 0 in
(x, n + 1) :: List.remove_assoc x acc) [] l in
List.iter (fun (k, n) -> Printf.printf "%d:%d " k n) (List.sort compare haeufigkeit);
print_newline ();
Printf.printf "%s\n" (String.concat "," (List.map string_of_int (List.sort_uniq compare l)))open_in/open_out, input_line, Fun.protect zum sicheren SchließenFormat für hübsche Ausgabe, Printf.sprintf für formatierte Stringsassert für schnelle Prüfungenlet () =
let datei = Filename.temp_file "ocaml" ".txt" in
let oc = open_out datei in
output_string oc "eins\nzwei\ndrei\n";
Printf.fprintf oc "Zahl: %d\n" 42;
close_out oc;
let ic = open_in datei in
(try
while true do
let zeile = input_line ic in
Printf.printf "> %s\n" zeile
done
with End_of_file -> close_in ic);
(* mit Hilfsfunktion, die die Datei zuverlässig schließt *)
let alle_zeilen pfad =
let ic = open_in pfad in
Fun.protect ~finally:(fun () -> close_in ic) (fun () ->
let rec lies acc = match input_line ic with
| z -> lies (z :: acc)
| exception End_of_file -> List.rev acc in
lies [])
in
Printf.printf "%d Zeilen\n" (List.length (alle_zeilen datei));
Sys.remove datei;
Printf.printf "%b\n" (Sys.file_exists datei)ref, mutable und Arraysmatchlet () =
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)]))