Syntax im Überblick
| Konzept | F# |
|---|---|
| Wert | let x = 5 |
| Veränderlich | let mutable x = 5, x <- 6 |
| Funktion | let f a b = a + b |
| Lambda | fun x -> x * 2 |
| Pipe | x |> f |> g |
| Komposition | f >> g |
| Liste / Array | [1; 2; 3] / [| 1; 2 |] |
| Tupel | (1, "a") |
| Record | { Name = "x"; Alter = 3 } |
| Union | type T = A | B of int |
| Option | Some 5, None |
| Match | match x with | A -> ... | _ -> ... |
| Klasse | type 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>.NameAusgabe
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 Int32Typische Fehler
let x = 1 + 2.0Fehlermeldung
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
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
Aufgabe
Portiere ein kleines C#-Programm nach F# und vergleiche den Umfang.