Skip to content

Instantly share code, notes, and snippets.

@CleanCoder
Created Jul 20, 2018
Embed
What would you like to do?
Funtional Programming
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