Skip to content

F# Folha de referência

Linguagem de programação funcional-first na plataforma .NET.

01

Primeiros passos

Hello World

printfn é a função de impressão padrão.

fsharp
printfn "Hello, World!"

Let Bindings

let é imutável; mutable + <- para valores mutáveis.

fsharp
let x = 10
let mutable y = 20
y <- 25

Funções

Funções são curried por padrão.

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

|> encaminha da esquerda para a direita, muito comum em 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 com 'with' para atualizações imutáveis.

fsharp
type Person = { Name: string; Age: int }
let p = { Name = "Alice"; Age = 30 }
let p2 = { p with Age = 31 }

Discriminated Unions

DUs são sum types; use match para tratamento exaustivo.

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 segurança contra 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

Coleções

Listas

O módulo List tem as operações padrão de FP.

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 são mutáveis; indexados com .[]

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

Sequences

seq é lazy, como IEnumerable.

fsharp
seq { 1..10 }
seq { for i in 1..10 do if i % 2 = 0 then yield i }

Was this helpful?