-
-
Save cartermp/8540e3fb1edf647f3c7ee8e4352c5941 to your computer and use it in GitHub Desktop.
This file contains 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
// First, define a 'zip' function | |
module Result = | |
let zip x1 x2 = | |
match x1,x2 with | |
| Ok x1res, Ok x2res -> Ok (x1res, x2res) | |
| Error e, _ -> Error e | |
| _, Error e -> Error e | |
// Next, define a builder with 'MergeSources' and 'BindReturn' | |
type ResultBuilder() = | |
member _.MergeSources(t1: Result<'T,'U>, t2: Result<'T1,'U>) = Result.zip t1 t2 | |
member _.BindReturn(x: Result<'T,'U>, f) = Result.map f x | |
let result = ResultBuilder() | |
let run r1 r2 r3 = | |
// And here is our applicative! | |
let res1: Result<int, string> = | |
result { | |
let! a = r1 | |
and! b = r2 | |
and! c = r3 | |
return a + b - c | |
} | |
match res1 with | |
| Ok x -> printfn "%s is: %d" (nameof res1) x | |
| Error e -> printfn "%s is: %s" (nameof res1) e | |
let printApplicatives () = | |
let r1 = Ok 2 | |
let r2 = Ok 3 // Error "fail!" | |
let r3 = Ok 4 | |
run r1 r2 r3 | |
run r1 (Error "failure!") r3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment