-
-
Save CleanCoder/fd27c8427472876f9dee0b282701eadb to your computer and use it in GitHub Desktop.
Funtional Programming
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
struct Result<T> { | |
public T Ok { get; } | |
public Exception Error { get; } | |
public bool IsFailed { get => Error != null; } | |
public bool IsOk => !IsFailed; | |
public Result (T ok) { | |
Ok = ok; | |
Error = default (Exception); | |
} | |
public Result (Exception error) { | |
Error = error; | |
Ok = default (T); | |
} | |
public R Match<R> (Func<T, R> okMap, Func<Exception, R> failureMap) => IsOk ? okMap (Ok) : failureMap (Error); | |
public void Match (Action<T> okAction, Action<Exception> errorAction) { | |
if (IsOk) okAction (Ok); | |
else errorAction (Error); | |
} | |
public static implicit operator Result<T> (T ok) => new Result<T> (ok); | |
public static implicit operator Result<T> (Exception error) => new Result<T> (error); | |
public static implicit operator Result<T> (Result.Ok<T> ok) => new Result<T> (ok.Value); | |
public static implicit operator Result<T> (Result.Failure error) => new Result<T> (error.Error); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment