Basics
3 snippetsF# fundamentals
Let Bindings
let name = "Alice"
let age = 30
let mutable counter = 0
counter <- counter + 1
printfn "Name: %s, Age: %d" name age Functions
let add x y = x + y
let square x = x * x
// Lambda
let double = fun x -> x * 2
// Pipe operator
[1..10] |> List.filter (fun x -> x % 2 = 0) |> List.sum Type Annotations
let greet (name: string) : string =
sprintf "Hello, %s!" name
let add (x: int) (y: int) : int = x + y Types
3 snippetsRecords, unions, and options
Records
type Person = {
Name: string
Age: int
Email: string option
}
let alice = { Name = "Alice"; Age = 30; Email = Some "a@b.com" }
let older = { alice with Age = 31 } Discriminated Unions
type Shape =
| Circle of radius: float
| Rectangle of width: float * height: float
| Triangle of base: float * height: float
let area shape =
match shape with
| Circle r -> System.Math.PI * r * r
| Rectangle (w, h) -> w * h
| Triangle (b, h) -> 0.5 * b * h Option & Result
let tryDivide x y =
if y = 0 then None
else Some (x / y)
let validate input =
if input > 0 then Ok input
else Error "Must be positive" Pattern Matching
3 snippetsMatch expressions and active patterns
Match
let describe x =
match x with
| 0 -> "zero"
| 1 -> "one"
| n when n < 0 -> "negative"
| _ -> "other" Destructuring
let (a, b) = (1, 2)
let { Name = name; Age = age } = alice
match myList with
| [] -> "empty"
| [x] -> sprintf "one: %A" x
| x :: rest -> sprintf "first: %A, rest: %d items" x (List.length rest) Active Patterns
let (|Even|Odd|) n =
if n % 2 = 0 then Even else Odd
let describe n =
match n with
| Even -> "even"
| Odd -> "odd" Tired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Collections
4 snippetsList, Array, Seq operations
List
let nums = [1; 2; 3; 4; 5]
let range = [1..10]
let evens = [for x in 1..10 do if x % 2 = 0 then yield x]
List.map (fun x -> x * 2) nums
List.filter (fun x -> x > 3) nums
List.fold (+) 0 nums // 15 Array
let arr = [| 1; 2; 3 |]
arr.[0] // 1
Array.map ((*) 2) arr
Array.sort arr Seq (lazy)
let infinite = Seq.initInfinite id
infinite |> Seq.take 5 |> Seq.toList
Seq.unfold (fun s -> if s > 100 then None else Some(s, s*2)) 1 Map & Set
let m = Map.ofList [("a", 1); ("b", 2)]
Map.find "a" m // 1
Map.add "c" 3 m
let s = Set.ofList [1; 2; 3]
Set.contains 2 s // true Async & Task
3 snippetsAsynchronous programming
Async Workflow
let fetchData url = async {
let! response = Http.AsyncRequestString(url)
return response.Length
}
let result = fetchData "https://example.com" |> Async.RunSynchronously Task (interop)
open System.Threading.Tasks
let fetchAsync () = task {
let! data = httpClient.GetStringAsync("https://api.example.com")
return data
} Parallel
let tasks = [1..10] |> List.map (fun i -> async { return i * i })
let results = tasks |> Async.Parallel |> Async.RunSynchronously