Created
April 9, 2014 01:10
-
-
Save otf/10215937 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
using System.Threading.Tasks; | |
using LangExt; | |
namespace LangExt.Guard | |
{ | |
public static class Control | |
{ | |
public static Result<TSuccess, TFailure> Guard<TSuccess, TFailure>(this Result<Placeholder, TFailure> it, bool cond, TFailure failure) | |
{ | |
if (cond) return it; | |
else return ((Result<TSuccess, TFailure>)it).Bind(m => Result.Failure(failure)); | |
} | |
public static Result<TSuccess, TFailure> Guard<TSuccess, TFailure>(this Result<TSuccess, Placeholder> it, bool cond, TFailure failure) | |
{ | |
if (cond) return it; | |
else return ((Result<TSuccess, TFailure>)it).Bind(m => Result.Failure(failure)); | |
} | |
public static Result<TSuccess, TFailure> Guard<TSuccess, TFailure>(this Result<TSuccess, TFailure> it, bool cond, TFailure failure) | |
{ | |
if(cond) return it; | |
else return it.Bind(m => Result.Failure(failure)); | |
} | |
public static Result<TSuccess, TFailure> Unless<TSuccess, TFailure>(this Result<Placeholder, TFailure> it, bool cond, TFailure failure) | |
{ | |
return it.Guard(!cond, failure); | |
} | |
public static Result<TSuccess, TFailure> Unless<TSuccess, TFailure>(this Result<TSuccess, Placeholder> it, bool cond, TFailure failure) | |
{ | |
return it.Guard(!cond, failure); | |
} | |
public static Result<TSuccess, TFailure> Unless<TSuccess, TFailure>(this Result<TSuccess, TFailure> it, bool cond, TFailure failure) | |
{ | |
return it.Guard(!cond, failure); | |
} | |
public static Option<T> Guard<T>(this Option<T> it, bool cond) | |
{ | |
return cond ? it : it.Bind(m => Option.None); | |
} | |
public static Option<T> Unless<T>(this Option<T> it, bool cond) | |
{ | |
return it.Guard(!cond); | |
} | |
public static Option<Unit> When(bool cond) | |
{ | |
return cond ? Option.Some() : Option.None; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var result = | |
Result.SuccessLazy(() => "succ") | |
.Guard(true, -1) | |
.Guard(true, -2) | |
.Guard(true, () => -3) | |
.Unless(true, -4); | |
var result2 = | |
Result.Failure(-1) | |
.Guard(true, -1) | |
.Guard(false, -2) | |
.Guard(false, -3) | |
.Unless(true, -4); | |
var opt = | |
Option.Some("a") | |
.Guard(true); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment