EMZETT.
Login

Kurz: > Achtung: Einrückung ist Syntax. Mische keine Tabs und Leerzeichen, und rücke fortlaufende Zeilen einer Funktion gleich weit ein. Auf Modulebene sind doppelte Namen (let x zweimal) nicht erlaubt.

Teil des Kurses F#

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

Syntax im Überblick

KonzeptF#
Wertlet x = 5
Veränderlichlet mutable x = 5, x <- 6
Funktionlet f a b = a + b
Lambdafun x -> x * 2
Pipex |> f |> g
Kompositionf >> g
Liste / Array[1; 2; 3] / [| 1; 2 |]
Tupel(1, "a")
Record{ Name = "x"; Alter = 3 }
Uniontype T = A | B of int
OptionSome 5, None
Matchmatch x with | A -> ... | _ -> ...
Klassetype K() = member ...
Interpolation$"Wert {x}"
let zeile (name: string) (wert: string) = printfn "%-26s %s" name wert
zeile "List.sum [1;2;3]" (string (List.sum [ 1; 2; 3 ]))
zeile "Seq.toList { 1..3 }" (sprintf "%A" (Seq.toList { 1 .. 3 }))
zeile "[1;2] @ [3]" (sprintf "%A" ([ 1; 2 ] @ [ 3 ]))
zeile "List.rev [1;2;3]" (sprintf "%A" (List.rev [ 1; 2; 3 ]))
zeile "Some 5 |> Option.map ((+) 1)" (sprintf "%A" (Some 5 |> Option.map ((+) 1)))
zeile "(1, 2) ||> (+)" (string ((1, 2) ||> (+)))
zeile "id 7, ignore 7" (sprintf "%d %A" (id 7) (ignore 7))
zeile "fst (1,2), snd (1,2)" (sprintf "%d %d" (fst (1, 2)) (snd (1, 2)))
zeile "min 3 9, max 3 9" (sprintf "%d %d" (min 3 9) (max 3 9))
zeile "string 3.5, float 2" (sprintf "%s %f" (string 3.5) (float 2))
zeile "Array.init 3 id" (sprintf "%A" (Array.init 3 id))
zeile "typeof<int>.Name" typeof<int>.Name

Ausgabe:

List.sum [1;2;3]           6
Seq.toList { 1..3 }        [1; 2; 3]
[1;2] @ [3]                [1; 2; 3]
List.rev [1;2;3]           [3; 2; 1]
Some 5 |> Option.map ((+) 1) Some 6
(1, 2) ||> (+)             3
id 7, ignore 7             7 ()
fst (1,2), snd (1,2)       1 2
min 3 9, max 3 9           3 9
string 3.5, float 2        3.5 2.000000
Array.init 3 id            [|0; 1; 2|]
typeof<int>.Name           Int32

Typische Fehler

let x = 1 + 2.0

Fehlermeldung:

The type 'float' does not match the type 'int'
let f x = x + 1
printfn "%d" (f "a")

Fehlermeldung:

This expression was expected to have type

Achtung

Einrückung ist Syntax. Mische keine Tabs und Leerzeichen, und rücke fortlaufende Zeilen einer Funktion gleich weit ein. Auf Modulebene sind doppelte Namen (let x zweimal) nicht erlaubt; in Funktionen dagegen schon (Shadowing).

Weiterführende Quellen

  • learn.microsoft.com/dotnet/fsharp: offizielle Dokumentation und Tour
  • fsharpforfunandprofit.com: das beste freie Lern-Material
  • fsharp.org: Community und Tools
  • „Domain Modeling Made Functional“ (Scott Wlaschin)

Merke

  • F# = funktionale Sprache auf .NET mit Typinferenz, Unions und Pipelines
  • Unveränderlichkeit und Pattern Matching machen Programme sicher und lesbar

Übungsaufgabe

Portiere ein kleines C#-Programm nach F# und vergleiche den Umfang.

Quiz zur Selbstkontrolle

Weiter im Kurs

Zurück: Praxis und Ökosystem

Alle Kapitel: F# im Überblick