01
Einstieg
Hello World
printfn ist die Standard-Ausgabefunktion.
fsharp
printfn "Hello, World!"let-Bindings
let ist unveränderlich; mutable plus <- für veränderliche Werte.
fsharp
let x = 10
let mutable y = 20
y <- 25Funktionen
Funktionen sind standardmäßig curried.
fsharp
let add a b = a + b
let result = add 3 4
// Explicit types
let divide (a: float) (b: float) : float = a / bPipe-Operator
|> leitet von links nach rechts weiter und ist in F# sehr verbreitet.
fsharp
[1; 2; 3; 4; 5]
|> List.filter (fun x -> x % 2 = 0)
|> List.map (fun x -> x * 2)
|> List.sum02
Typen
Records
Records mit 'with' für unveränderliche Aktualisierungen.
fsharp
type Person = { Name: string; Age: int }
let p = { Name = "Alice"; Age = 30 }
let p2 = { p with Age = 31 }Discriminated Unions
DUs sind Summentypen; match für erschöpfende Behandlung.
fsharp
type Shape =
| Circle of radius: float
| Rectangle of w: float * h: float
let area s =
match s with
| Circle r -> 3.14 * r * r
| Rectangle (w, h) -> w * hOption
Option<T> = Some T | None für Null-Sicherheit.
fsharp
let safeDiv a b =
if b = 0 then None else Some (a / b)
match safeDiv 10 2 with
| Some v -> printfn "%d" v
| None -> printfn "error"03
Collections
Listen
Das List-Modul bietet die üblichen FP-Operationen.
fsharp
let xs = [1; 2; 3; 4; 5]
List.map (fun x -> x * 2) xs
List.filter (fun x -> x > 2) xs
List.fold (+) 0 xsArrays
Arrays sind veränderlich; Indizierung mit .[]
fsharp
let arr = [|1; 2; 3|]
arr.[0] <- 10Sequenzen
seq ist lazy, wie IEnumerable.
fsharp
seq { 1..10 }
seq { for i in 1..10 do if i % 2 = 0 then yield i }Was this helpful?