01
Primeros pasos
Hello World
printfn es la función de impresión estándar.
fsharp
printfn "Hello, World!"Declaraciones let
let es inmutable; mutable + <- para valores mutables.
fsharp
let x = 10
let mutable y = 20
y <- 25Funciones
Las funciones están curried por defecto.
fsharp
let add a b = a + b
let result = add 3 4
// Explicit types
let divide (a: float) (b: float) : float = a / bOperador pipe
|> canaliza de izquierda a derecha, muy común en F#.
fsharp
[1; 2; 3; 4; 5]
|> List.filter (fun x -> x % 2 = 0)
|> List.map (fun x -> x * 2)
|> List.sum02
Tipos
Records
Records con 'with' para actualizaciones inmutables.
fsharp
type Person = { Name: string; Age: int }
let p = { Name = "Alice"; Age = 30 }
let p2 = { p with Age = 31 }Discriminated Unions
Las DUs son tipos suma; match para un manejo exhaustivo.
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 para seguridad frente a nulos.
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
Colecciones
Lists
El módulo List tiene las operaciones funcionales estándar.
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
Los arrays son mutables; se indexan con .[]
fsharp
let arr = [|1; 2; 3|]
arr.[0] <- 10Sequences
seq es perezoso, similar a IEnumerable.
fsharp
seq { 1..10 }
seq { for i in 1..10 do if i % 2 = 0 then yield i }Was this helpful?