Skip to content

Instantly share code, notes, and snippets.

@jbrestan
Created September 29, 2016 11:31
Show Gist options
  • Save jbrestan/a129cf1d525a3cbb7f51ec54d1bf7d67 to your computer and use it in GitHub Desktop.
Save jbrestan/a129cf1d525a3cbb7f51ec54d1bf7d67 to your computer and use it in GitHub Desktop.
type Result<'result, 'message> =
| Success of 'result
| Failure of 'message list
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module Result =
let inline succeed v =
Success v
let inline fail msg =
Failure [msg]
let inline mapR (f: 'a -> 'b) (result: Result<'a, 'c>) =
match result with
| Success x -> Success <| f x
| Failure errors -> Failure errors
let inline (<!>) r f = mapR f r
let inline applyR (f: Result<'a -> 'b, 'c>) (result: Result<'a, 'c>) =
match f,result with
| Success f, r -> r <!> f
| Failure errors, Success _ ->
Failure errors
| Failure errors1, Failure errors2 ->
Failure <| errors1 @ errors2
let inline (<*>) f r = applyR f r
let inline bindR (f: 'a -> Result<'b, 'c>) (result: Result<'a, 'c>) =
match result with
| Success x -> f x
| Failure errors -> Failure errors
let inline (>>=) r f = bindR f r
let inline composeR (f: 'a -> Result<'b, 'e>) (g: 'b -> Result<'c, 'e>) (x: 'a) =
match f x with
| Success y -> g y
| Failure e -> Failure e
let inline (>=>) f g = composeR f g
type ResultBuilder () =
member inline this.Bind (m, f) = m >>= f
member inline this.Return a = succeed a
member inline this.ReturnFrom m = m
member inline this.Zero() = this.Return ()
member inline this.Delay(f) = f
member inline this.Run(r) = r ()
member inline this.TryWith(body, handler) =
try this.ReturnFrom(body ())
with e -> handler e
member inline this.TryFinally(body, compenstaion) =
try this.ReturnFrom(body ())
finally compenstaion ()
[<AutoOpen>]
module ResultCE =
let result = Result.ResultBuilder()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment