From fd9efaa01ab26bc9eb90d1d74ccc06761212e225 Mon Sep 17 00:00:00 2001 From: Mohammad Sepahvand Date: Sun, 10 Jan 2021 01:51:19 +1100 Subject: [PATCH] Add an example of combining Map() and Bind() to README --- README.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/README.md b/README.md index 7345f23..da7de9f 100644 --- a/README.md +++ b/README.md @@ -130,3 +130,33 @@ Try t2 = t1.Map(v1 => return v1.Value + 10; }); ``` + +### Short Circuit failure paths + +A powerful way of using this monad is by combining `Map()` and `Bind()`. Aside from making the code more fluent, the execution path will short circuit and return as soon as a failure state is encountered: + +```C# +Try tryResult = Increment1(1) + .Bind(Increment2) + .Map(Increment3); + +string result = tryResult.Match( + exception => $"Failed: {exception.Message}", + value => $"Passed: {value}"); + +private static Try Increment1(int x) +{ + return Try.Create(() => x + 1); +} + +private static Try Increment2(int x) +{ + return Try.FromException(new Exception("Failed!")); +} + +// This method will never get executed since the previous method threw an exception +private static int Increment3(int x) +{ + return x + 3; +} +``` \ No newline at end of file