export interface Attempt { readonly foldAttempt: (onFailed: (e: E) => B, onPassed: (a: A) => B) => B; } const failed = (err: E): Attempt => { return { foldAttempt: (onFailed, _onPassed) => { return onFailed(err); } }; }; const passed = (value: A): Attempt => { return { foldAttempt: (onFailed, onPassed) => { return onPassed(value); } }; }; const cata = (attempt: Attempt, onFailed: (e: E) => B, onPassed: (a: A) => B): B => { return attempt.foldAttempt(onFailed, onPassed); }; const bind = (firstAttempt: Attempt, f: (a: A) => Attempt): Attempt => { return firstAttempt.foldAttempt>(failed, f); }; const map = (firstAttempt: Attempt, f: (a: A) => B): Attempt => { return firstAttempt.foldAttempt>(failed, (v) => passed(f(v))); }; const list = (firstAttempt: Attempt, fs: Array<(a: A) => Attempt>): Attempt => { return fs.reduce((rest, x) => { return bind(rest, x); }, firstAttempt); }; const carry = (firstAttempt: Attempt, secondAttempt: Attempt, f: (a: A, b: B) => Attempt): Attempt => { return cata(firstAttempt, (errs) => { return cata(secondAttempt, (sErrs) => { return failed(errs.concat(sErrs)); }, (_) => { return failed(errs); }); }, (fValue) => { return cata(secondAttempt, (sErrs) => { return failed(sErrs); }, (sValue) => { return f(fValue, sValue); }); }); }; const concat = (attempts: Array>): Attempt => { // take a list of attempts, and turn them info an attempt of a list. return attempts.reduce((rest: Attempt, b) => { return carry(rest, b, (x, y) => { return passed(x.concat([y])); }); }, passed([] as A[])); }; const toString = (attempt: Attempt): string => { return cata(attempt, (errs) => { return 'attempt.failed(' + JSON.stringify(errs) + ')'; }, (value) => { return 'attempt.passed(' + JSON.stringify(value) + ')'; }); }; const hasPassed = (attempt: Attempt): boolean => { return cata(attempt, () => false, () => true); }; export const Attempt = { failed, passed, cata, bind, map, list, carry, concat, toString, hasPassed };