Skip to content

Instantly share code, notes, and snippets.

@throughnothing
Created May 17, 2020 04:45
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 throughnothing/747997a3649e81fb482105735e9ee5d0 to your computer and use it in GitHub Desktop.
Save throughnothing/747997a3649e81fb482105735e9ee5d0 to your computer and use it in GitHub Desktop.
very simple Either in Typescript
export interface Either<E, A> {
map<B>(f: (a: A) => B): Either<E, B>;
mapLeft<F>(f: (e: E) => F): Either<F, A>;
flatMap<B>(f: (a: A) => Either<E, B>): Either<E, B>;
flatMapLeft<F>(f: (e: E) => Either<F, A>): Either<F, A>;
ap<B>(f: Either<E, (a: A) => B>): Either<E, B>;
match<R>(result: (success: A) => R, error: (err: E) => R): R;
}
export class Left<E, A> implements Either<E, A> {
readonly _tag: 'Left' = 'Left';
constructor(readonly left: E) {}
map<B>(f: (a: A) => B): Either<E, B> {
return new Left(this.left);
}
mapLeft<F>(f: (e: E) => F): Either<F, A> {
return new Left(f(this.left))
}
flatMap<B>(f: (a: A) => Either<E, B>): Either<E, B> {
return new Left(this.left);
}
flatMapLeft<F>(f: (e: E) => Either<F, A>): Either<F, A> {
return f(this.left);
}
ap<B>(f: Either<E, (a: A) => B>): Either<E, B> {
return new Left(this.left);
}
match<R>(result: (success: A) => R, error: (err: E) => R): R {
return error(this.left)
}
}
export class Right<E, A> implements Either<E, A> {
readonly _tag: 'Right' = 'Right';
constructor(readonly right: A) {}
map<B>(f: (a: A) => B): Either<E, B> {
return new Right(f(this.right));
}
mapLeft<F>(f: (e: E) => F): Either<F, A> {
return new Right(this.right);
}
flatMap<B>(f: (a: A) => Either<E, B>): Either<E, B> {
return f(this.right);
}
flatMapLeft<F>(f: (e: E) => Either<F, A>): Either<F, A> {
return new Right(this.right);
}
ap<B>(e: Either<E, (a: A) => B>): Either<E, B> {
return e.flatMap(f => this.map(f))
}
match<R>(result: (success: A) => R, error: (err: E) => R): R {
return result(this.right)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment