Skip to content

F# Spickzettel

Funktional-first-Programmiersprache auf der .NET-Plattform.

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 <- 25

Funktionen

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 / b

Pipe-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.sum
02

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 * h

Option

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 xs

Arrays

Arrays sind veränderlich; Indizierung mit .[]

fsharp
let arr = [|1; 2; 3|]
arr.[0] <- 10

Sequenzen

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?