Skip to content

Instantly share code, notes, and snippets.

@christianscott
Created October 19, 2019 05:04
Show Gist options
  • Save christianscott/12dec1d713f00a16fc0fb5b340547e14 to your computer and use it in GitHub Desktop.
Save christianscott/12dec1d713f00a16fc0fb5b340547e14 to your computer and use it in GitHub Desktop.
export module Maybe {
enum MaybeKind {
SOME = 1,
NOTHING,
}
export type Nothing = { kind: MaybeKind.NOTHING };
export type Some<T> = { kind: MaybeKind.SOME; value: T };
export type t<T> = Some<T> | Nothing;
export const nothing = (): Nothing => ({ kind: MaybeKind.NOTHING });
export const some = <T>(value: T): Some<T> => ({ kind: MaybeKind.SOME, value });
export const isNothing = <T>(maybe: t<T>): maybe is Nothing => maybe.kind === MaybeKind.NOTHING;
export const isSome = <T>(maybe: t<T>): maybe is Some<T> => maybe.kind === MaybeKind.SOME;
}
export module Result {
enum ResultKind {
ERR,
OK
}
export type Err<E> = {kind: ResultKind.ERR; err: E}
export type Ok<T> = {kind: ResultKind.OK; value: T}
export type t<T, E> = Ok<T> | Err<E>
export const err = <E>(e: E): Err<E> => ({kind: ResultKind.ERR, err: e})
export const ok = <T>(value: T): Ok<T> => ({kind: ResultKind.OK, value})
export const isOk = <T, E>(result: t<T, E>): result is Ok<T> =>
result.kind === ResultKind.OK
export const isErr = <T, E>(result: t<T, E>): result is Err<E> =>
result.kind === ResultKind.ERR
export const map = <A, B, E>(result: t<A, E>, fn: (a: A) => B): t<B, E> =>
isOk(result) ? ok(fn(result.value)) : result
export const mapErr = <A, E, F>(result: t<A, E>, fn: (e: E) => F): t<A, F> =>
isErr(result) ? err(fn(result.err)) : result
type Matcher<A, B, E, F> = {
ok(a: A): B
err(e: E): F
}
export const match = <A, B, E, F>(
result: t<A, E>,
matcher: Matcher<A, B, E, F>
): t<B, F> =>
isOk(result) ? ok(matcher.ok(result.value)) : err(matcher.err(result.err))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment