Skip to content

Files

Latest commit

a8518ff · Sep 25, 2019

History

History
178 lines (150 loc) · 3.19 KB

fsharp.md

File metadata and controls

178 lines (150 loc) · 3.19 KB

F# Cheatsheet

Resources

Articles

Videos

Types

Arrays

Declare an array

let alpha = [| 'A' .. 'Z' |]
let alpha = [| 'A' ; 'Z' |]
let results = [| for i in 1 .. 64 -> square i |]

2D arrays as class members

type DemData(width, height) =
    member this.Cells = Array2D.create width height NoHeight

Access array elements by index

alpha.[index]

Sequences

Exists

input |> Seq.exists(fun c -> Char.IsLower c)

Sum by

results |> Seq.sumBy(fun res -> extractValue res)

Sets

Declare an empty set

let usedRobotNames: Set<string> = Set.empty

Convert a list to set

let allChars = [ 'a' .. 'z' ] |> Set

Size of the set

Set.count usedChars

Set contains

Set.contains candidateName usedRobotNames

Is subset

Set.isSubset smallerSet biggerSet

Add to set

let mutable usedRobotNames: Set<string> = Set.empty

usedRobotNames <- Set.add chosenName usedRobotNames

Set map

let usedChars = Set.ofSeq input
    |> Set.map (Char.ToLower)

Type aliases

Used for functions

type FetchSrtmTiles = SrtmTileCoords seq -> SrtmTileHgtFile seq

Tuples

type SrtmTileHgtFile = SrtmTileCoords * string

Records

type Bounds = { 
    MinLon: double
    MinLat: double 
    MaxLon: double 
    MaxLat: double
    }

Creating records

let bounds = { 
    MinLon = 10.1; MinLat = 20.1; 
    MaxLon = 10.2; MaxLat = 20.2
}

Empty record

type NoHeight = NoHeight of unit

Single-case union types

type SrtmTileHgtFile = SrtmTileHgtFile of SrtmTileCoords * string

Creating

SrtmTileHgtFile (tileCoords, Path.Combine(localCacheDir, tileHgtFileName))

Classes

type Robot (name: string) =
    member this.Name = name

Constructs

Match

With when

match radius with
    | r when r > 10.0 -> 0
    | r when r > 5.0 -> 1
    | r when r > 1.0 -> 5
    | _ -> 10

Unit testing

xUnit

Defining test fixture class and constructor

type ``PNG filtering property tests``() = 
    do 
        Arb.register<ScanlinesGenerator>() |> ignore

FSUnit

|> should equal "N10W001"
stream |> should not' (equal None)
demData |> should be ofExactType<DemData>

Unquote

Asserting exceptions

    raises<InvalidOperationException> 
        <@ 
            decodeSrtmTileFromPngFile FileSys.openFileToRead pngFileName 
        @>

FSCheck

Registering generators inside test fixture contructor

type ``PNG filtering property tests``() = 
    do 
        Arb.register<ScanlinesGenerator>() |> ignore