Created
March 29, 2022 01:47
-
-
Save shovon/77cec60163e65d24960482c28b2fa7db to your computer and use it in GitHub Desktop.
Lisp-style cons-based list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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