Created
September 27, 2020 15:55
-
-
Save SchlenkR/1590768134bb8abe53213be8f168e048 to your computer and use it in GitHub Desktop.
F# Standard Builder Methods (Template)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// stolen from: https://fsharpforfunandprofit.com/posts/computation-expressions-builder-part6/ | |
type WhateverBuilder() = | |
member this.Bind(m, f) = m f | |
member this.Return(x) = x | |
member this.ReturnFrom(x) = x | |
member this.Yield(x) = this.Return (x) | |
member this.YieldFrom(x) = x | |
member this.Zero() = this.Return () | |
member this.Delay(f) = f | |
member this.Run(f) = f() | |
member this.While(guard, body) = | |
if not (guard()) | |
then this.Zero() | |
else this.Bind( body(), fun () -> | |
this.While(guard, body)) | |
member this.TryWith(body, handler) = | |
try this.ReturnFrom(body()) | |
with e -> handler e | |
member this.TryFinally(body, compensation) = | |
try this.ReturnFrom(body()) | |
finally compensation() | |
member this.Using(disposable:#System.IDisposable, body) = | |
let body' = fun () -> body disposable | |
this.TryFinally(body', fun () -> | |
match disposable with | |
| null -> () | |
| disp -> disp.Dispose()) | |
member this.For(sequence:seq<_>, body) = | |
this.Using(sequence.GetEnumerator(),fun enum -> | |
this.While(enum.MoveNext, | |
this.Delay(fun () -> body enum.Current))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment