Skip to content

Instantly share code, notes, and snippets.

@guneysus
Forked from CleanCoder/FP
Last active April 8, 2020 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guneysus/09f93eb54085b8e8185ef0e55179be16 to your computer and use it in GitHub Desktop.
Save guneysus/09f93eb54085b8e8185ef0e55179be16 to your computer and use it in GitHub Desktop.
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