01
Démarrage
Hello World
printfn est la fonction d'affichage standard.
fsharp
printfn "Hello, World!"Liaisons let
let est immuable ; mutable + <- pour les valeurs modifiables.
fsharp
let x = 10
let mutable y = 20
y <- 25Fonctions
Les fonctions sont curried par défaut.
fsharp
let add a b = a + b
let result = add 3 4
// Explicit types
let divide (a: float) (b: float) : float = a / bOpérateur pipe
|> enchaîne de gauche à droite, très courant en F#.
fsharp
[1; 2; 3; 4; 5]
|> List.filter (fun x -> x % 2 = 0)
|> List.map (fun x -> x * 2)
|> List.sum02
Types
Records
Records avec 'with' pour des mises à jour immuables.
fsharp
type Person = { Name: string; Age: int }
let p = { Name = "Alice"; Age = 30 }
let p2 = { p with Age = 31 }Discriminated Unions
Les DUs sont des types somme ; match garantit un traitement exhaustif.
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 pour la sécurité face aux null.
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
Listes
Le module List fournit les opérations fonctionnelles standards.
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 xsTableaux
Les tableaux sont modifiables ; indexation avec .[]
fsharp
let arr = [|1; 2; 3|]
arr.[0] <- 10Séquences
seq est paresseux, comme IEnumerable.
fsharp
seq { 1..10 }
seq { for i in 1..10 do if i % 2 = 0 then yield i }Was this helpful?