FSharpPlus


Computations Expressions

This library allows to use some common computation expressions without writing any boiler plate code.

There is a single computation expression: monad but it comes in 4 flavours:

In other words:

Note that a type is either lazy or strict, but it could act as fx or plus at the same time (see below some examples). This means that we need to pay attention when using a CE over a type, if the type is lazy but with use a strict monad, we'll get strict semantics which probably would make no sense, but if we do the opposite we might run into runtime errors, fortunately a compile-time warning (or error) will prevent us.

A simple way to find out if a type is strict or lazy is to execute this in fsi: let _ : MyType<'t> = monad { printfn "I'm strict" }

For layered monads (monad transformers) the general rule is: the monad is strict unless at least one of its constituent types is lazy, in that case the whole monad becomes lazy.

let _ : OptionT<list<unit option>> = monad { printfn "I'm strict" }
// will print I'm strict, because OptionT and list are strict

let _ : OptionT<seq<unit option>> = monad { printfn "I'm strict" }
// won't print anything, because seq is lazy

Applicatives

There are some F# issues preventing applicative required BindReturn to be included in monad, so for the moment the following snipped can be used to quickly create a generic applicative CE:

type ApplicativeBuilder<'t> () =
    inherit MonadFxStrictBuilder<'t> ()
    member inline _.BindReturn (x, f) = map f x

let applicative<'t> = ApplicativeBuilder<'t> ()

Examples

You may run this script step-by-step.

#r @"nuget: FSharpPlus"
open FSharpPlus

let lazyValue = monad {
    let! a = lazy (printfn "I'm lazy"; 2)
    let! b = lazy (printfn "I'm lazy too"; 10)
    return a + b}

// val lazyValue : System.Lazy<int> = Value is not created.

let res12 = lazyValue.Value


let maybeWithSideFx = monad' { 
    let! a = Some 3
    let b = ref 0
    while !b < 10 do 
        let! n = Some ()
        incr b
    if a = 3 then printfn "got 3"
    else printfn "got something else (will never print this)"
    return a }

// val maybeWithSideFx : int option = Some 3



let lst = [None; None; Some 2; Some 4; Some 10; None]

let maybeManyTimes = monad.plus' {
    let defaultValue = 42
    let mutable i = 0
    return! None
    while i < 5 do
        printfn "looping %i" i
        i <- i + 1
        return! lst.[i]
    printfn "halfway"
    return! None
    printfn "near the end"
    return defaultValue }

// val maybeManyTimes : int option = Some 2


let (asnNumber: Async<_>) = monad.fx {
    let mutable m = ResizeArray ()
    try
        for i = 1 to 10 do
            m.Add i
        return m.[-1]
    with e ->
        return -3 }


let (lstNumber: list<_>) = monad.plus' {
    try
        for i = 1 to 10 do
            return i
    with e ->
        return -3 }


(*
For more information about computation expressions you can read the paper : The F# Computation Expression Zoo
http://tomasp.net/academic/papers/computation-zoo/computation-zoo.pdf
*)
namespace FSharpPlus
namespace FSharpPlus.Data
Multiple items
union case OptionT.OptionT: 'monad<option<'t>> -> OptionT<'monad<option<'t>>>

--------------------
module OptionT from FSharpPlus.Data
<summary> Basic operations on OptionT </summary>

--------------------
[<Struct>] type OptionT<'monad<option<'t>>> = | OptionT of 'monad<option<'t>> static member (<*>) : f: OptionT<'Monad<option<('T -> 'U)>> * x: OptionT<'Monad<option<'T>> -> OptionT<'Monad<option<'U>> (requires member Map and member ``<*>``) static member (<|>) : OptionT<'a1> * OptionT<'MonadPlus<option<'T>> -> OptionT<'MonadPlus<option<'T>> (requires member (>>=) and member Return) static member (>>=) : x: OptionT<'Monad<option<'T>> * f: ('T -> OptionT<'Monad<option<'U>>) -> OptionT<'Monad<option<'U>> (requires member (>>=) and member Return) static member CallCC: f: (('T -> OptionT<'MonadCont<'R,option<'U>>>) -> OptionT<'MonadCont<'R,option<'T>>>) -> OptionT<'MonadCont<'R,option<'T>>> (requires member CallCC) static member Catch: m: OptionT<'MonadError<'E1,'T>> * h: ('E1 -> OptionT<'MonadError<'E2,'T>>) -> OptionT<'MonadError<'E2,'T>> (requires member Catch) static member Delay: body: (unit -> OptionT<'Monad<option<'T>>>) -> OptionT<'Monad<option<'T>>> (requires member Delay) static member LiftAsync: x: Async<'T> -> OptionT<'MonadAsync<'T>> (requires member Return and member (>>=) and member Map and member LiftAsync) static member Listen: m: OptionT<'a1> -> OptionT<''MonadWriter<'Monoid, option<'T>>> (requires member (>>=) and member Return and member Listen) static member Local: OptionT<'MonadReader<'R2,'T>> * f: ('R1 -> 'R2) -> OptionT<'a4> (requires member Local) static member Pass: m: OptionT<'a1> -> OptionT<'MonadWriter<'Monoid, option<'T>>> (requires member (>>=) and member Map and member Return and member Pass and member Return) ...
<summary> Monad Transformer for Option&lt;'T&gt; </summary>
type 'T list = List<'T>
<summary>The type of immutable singly-linked lists. </summary>
<remarks>See the <see cref="T:Microsoft.FSharp.Collections.ListModule" /> module for further operations related to lists. Use the constructors <c>[]</c> and <c>::</c> (infix) to create values of this type, or the notation <c>[1; 2; 3]</c>. Use the values in the <c>List</c> module to manipulate values of this type, or pattern match against the values directly. See also <a href="https://docs.microsoft.com/dotnet/fsharp/language-reference/lists">F# Language Guide - Lists</a>. </remarks>
type unit = Unit
<summary>The type 'unit', which has only one value "()". This value is special and always uses the representation 'null'.</summary>
<category index="1">Basic Types</category>
Multiple items
val option: f: ('g -> 'h) -> n: 'h -> _arg1: 'g option -> 'h
<summary> Takes a function, a default value and a option value. If the option value is None, the function returns the default value. Otherwise, it applies the function to the value inside Some and returns the result. </summary>
<category index="0">Common Combinators</category>


--------------------
type 'T option = Option<'T>
<summary>The type of optional values. When used from other CLI languages the empty option is the <c>null</c> value. </summary>
<remarks>Use the constructors <c>Some</c> and <c>None</c> to create values of this type. Use the values in the <c>Option</c> module to manipulate values of this type, or pattern match against the values directly. 'None' values will appear as the value <c>null</c> to other CLI languages. Instance methods on this type will appear as static methods to other CLI languages due to the use of <c>null</c> as a value representation.</remarks>
<category index="3">Options</category>
val monad<'monad<'t>> : MonadFxBuilder<'monad<'t>>
<summary> Creates a (lazy) monadic computation expression with side-effects (see http://fsprojects.github.io/FSharpPlus/computation-expressions.html for more information) </summary>
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
<summary>Print to <c>stdout</c> using the given format, and add a newline.</summary>
<param name="format">The formatter.</param>
<returns>The formatted result.</returns>
<example>See <c>Printf.printfn</c> (link: <see cref="M:Microsoft.FSharp.Core.PrintfModule.PrintFormatLine``1" />) for examples.</example>
Multiple items
val seq: sequence: seq<'T> -> seq<'T>
<summary>Builds a sequence using sequence expression syntax</summary>
<param name="sequence">The input sequence.</param>
<returns>The result sequence.</returns>
<example id="seq-cast-example"><code lang="fsharp"> seq { for i in 0..10 do yield (i, i*i) } </code></example>


--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>
<summary>An abbreviation for the CLI type <see cref="T:System.Collections.Generic.IEnumerable`1" /></summary>
<remarks> See the <see cref="T:Microsoft.FSharp.Collections.SeqModule" /> module for further operations related to sequences. See also <a href="https://docs.microsoft.com/dotnet/fsharp/language-reference/sequences">F# Language Guide - Sequences</a>. </remarks>
Multiple items
type ApplicativeBuilder<'t> = inherit MonadFxStrictBuilder<'t> new: unit -> ApplicativeBuilder<'t> member BindReturn: x: 'a * f: ('c -> 'd) -> 'b (requires member Map)

--------------------
new: unit -> ApplicativeBuilder<'t>
Multiple items
type MonadFxStrictBuilder<'monad<'t>> = inherit StrictBuilder<'monad<'t>> new: unit -> MonadFxStrictBuilder<'monad<'t>> member Combine: a: 'Monad<unit> * b: (unit -> 'Monad<'T>) -> 'Monad<'T> (requires member (>>=)) member For: p: #seq<'T> * rest: ('T -> 'Monad<unit>) -> 'Monad<unit> (requires member Using and member Return and member (>>=)) member While: guard: (unit -> bool) * body: (unit -> 'Monad<unit>) -> 'Monad<unit> (requires member (>>=) and member Return) member Zero: unit -> 'Monad<unit> (requires member Return)

--------------------
new: unit -> MonadFxStrictBuilder<'monad<'t>>
val x: 'a (requires member Map)
val f: ('c -> 'd)
val map: f: ('T -> 'U) -> x: 'Functor<'T> -> 'Functor<'U> (requires member Map)
<summary>Lifts a function into a Functor.</summary>
<category index="1">Functor</category>
val applicative<'t> : ApplicativeBuilder<'t>
val lazyValue: System.Lazy<int>
val a: int
val b: int
val res12: int
property System.Lazy.Value: int with get
val maybeWithSideFx: int option
union case Option.Some: Value: 'T -> Option<'T>
<summary>The representation of "Value of type 'T"</summary>
<param name="Value">The input value.</param>
<returns>An option representing the value.</returns>
val b: int ref
Multiple items
val ref: value: 'T -> 'T ref
<summary>Create a mutable reference cell</summary>
<param name="value">The value to contain in the cell.</param>
<returns>The created reference cell.</returns>
<example id="ref-example"><code lang="fsharp"> let count = ref 0 // Creates a reference cell object with a mutable Value property count.Value // Evaluates to 0 count.Value &lt;- 1 // Updates the value count.Value // Evaluates to 1 </code></example>


--------------------
type 'T ref = Ref<'T>
<summary>The type of mutable references. Use the functions [!] and [:=] to get and set values of this type.</summary>
<category>Basic Types</category>
val n: unit
val incr: cell: int ref -> unit
<summary>Increment a mutable reference cell containing an integer</summary>
<param name="cell">The reference cell.</param>
<example id="incr-example"><code lang="fsharp"> let count = ref 99 // Creates a reference cell object with a mutable Value property incr count // Increments our counter count.Value // Evaluates to 100 </code></example>
val lst: int option list
union case Option.None: Option<'T>
<summary>The representation of "No value"</summary>
val maybeManyTimes: int option
val defaultValue: int
val mutable i: int
val asnNumber: Async<int>
Multiple items
module Async from FSharpPlus
<summary> Additional operations on Async </summary>

--------------------
type Async = static member AsBeginEnd: computation: ('Arg -> Async<'T>) -> ('Arg * AsyncCallback * obj -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit) static member AwaitEvent: event: IEvent<'Del,'T> * ?cancelAction: (unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate) static member AwaitIAsyncResult: iar: IAsyncResult * ?millisecondsTimeout: int -> Async<bool> static member AwaitTask: task: Task<'T> -> Async<'T> + 1 overload static member AwaitWaitHandle: waitHandle: WaitHandle * ?millisecondsTimeout: int -> Async<bool> static member CancelDefaultToken: unit -> unit static member Catch: computation: Async<'T> -> Async<Choice<'T,exn>> static member Choice: computations: seq<Async<'T option>> -> Async<'T option> static member FromBeginEnd: beginAction: (AsyncCallback * obj -> IAsyncResult) * endAction: (IAsyncResult -> 'T) * ?cancelAction: (unit -> unit) -> Async<'T> + 3 overloads static member FromContinuations: callback: (('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T> ...
<summary>Holds static members for creating and manipulating asynchronous computations.</summary>
<remarks> See also <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/asynchronous-workflows">F# Language Guide - Async Workflows</a>. </remarks>
<category index="1">Async Programming</category>


--------------------
type Async<'T>
<summary> An asynchronous computation, which, when run, will eventually produce a value of type T, or else raises an exception. </summary>
<remarks> This type has no members. Asynchronous computations are normally specified either by using an async expression or the static methods in the <see cref="T:Microsoft.FSharp.Control.FSharpAsync`1" /> type. See also <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/asynchronous-workflows">F# Language Guide - Async Workflows</a>. </remarks>
<namespacedoc><summary> Library functionality for asynchronous programming, events and agents. See also <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/asynchronous-workflows">Asynchronous Programming</a>, <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/members/events">Events</a> and <a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/lazy-expressions">Lazy Expressions</a> in the F# Language Guide. </summary></namespacedoc>
<category index="1">Async Programming</category>
val mutable m: ResizeArray<int>
Multiple items
module ResizeArray from FSharpPlus
<summary> Additional operations on ResizeArray </summary>

--------------------
type ResizeArray<'T> = System.Collections.Generic.List<'T>
<summary>An abbreviation for the CLI type <see cref="T:System.Collections.Generic.List`1" /></summary>
val i: int
System.Collections.Generic.List.Add(item: int) : unit
val e: exn
val lstNumber: int list