Skip to content

F# Hoja de referencia

Lenguaje de programación funcional en primer lugar sobre la plataforma .NET.

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

Funciones

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

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

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

Option

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 xs

Arrays

Los arrays son mutables; se indexan con .[]

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

Sequences

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?