Skip to content

Instantly share code, notes, and snippets.

@shovon
Created March 29, 2022 01:47
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 shovon/77cec60163e65d24960482c28b2fa7db to your computer and use it in GitHub Desktop.
Save shovon/77cec60163e65d24960482c28b2fa7db to your computer and use it in GitHub Desktop.
Lisp-style cons-based list
type List<T1> = [T1, List<T1> | null];
function* iterateCons<T>([left, right]: List<T>): IterableIterator<T> {
if (right) {
yield* iterateCons(right);
}
yield left;
}
const cons = <T1, T2>(left: T1, right: T2): [T1, T2] => [left, right];
const list = <T>(l?: List<T>) => ({
append: (v: T) => list(cons(v, l ?? null)),
[Symbol.iterator]: () =>
l ? iterateCons(l) : { next: () => ({ value: null, done: true }) },
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment