Skip to content

F# Tips & Tricks

Attila Szabo edited this page Dec 25, 2023 · 1 revision

Collection of some simple F# constructs that may or may not be known by some people.

Double pipe operator

Very useful for things like AVal.map2:

(x, y) ||> AVal.map (fun a b -> a + b)

Lets you pipe mutiple arguments into a function, which can make your code more readable and does not require any type annotations in the lambda function. Also exists for three arguments (|||>).

Function composition

Lets you compose simple functions without having to write a lambda function explicitly:

arrayOfFloatTuples |> Array.map (fst >> sqrt)

instead of

arrayOfFloatTuples |> Array.map (fun (x, y) -> sqrt x)

Backwards pipe

All the pipe and function composition operators have backwards variants, which can be used to avoid parentheses. Especially, in media applications this seems to be quite useful:

always <| style "width: 100%; grid-row: 2; height:100%"
Incremental.div AttributeMap.empty <| alist {
    let! position = model.location
    if position = Position.Top then 
        yield aard "top"
}

https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/symbol-and-operator-reference/#function-symbols-and-operators

Function keyword

More concise syntax for a function with pattern matching:

let depthTest =
    style |> AVal.bind (fun x ->
        match x with
        | RenderStyle.Normal -> AVal.constant DepthTest.None
        | _ -> scope.DepthTest
    )

can be simplified as follows:

let depthTest =
    style |> AVal.bind (function
        | RenderStyle.Normal -> AVal.constant DepthTest.None
        | _ -> scope.DepthTest
    )  

https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/match-expressions

Clone this wiki locally