Last active
September 19, 2019 18:07
-
-
Save venil7/8e0513592dfb57a83bd5d1d46ec42d30 to your computer and use it in GitHub Desktop.
TypeScript Linked List (Haskell/OCaml)
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 Item<T> = { val: T, rest: List<T> } | null; | |
type List<T> = Item<T>; | |
const cons = <T>(val: T, rest: List<T>) => ({ val, rest }); | |
const empty = () => null; | |
const fold_left = <T, A>(func: (acc: A, val: T) => A, list: List<T>, acc: A): A => { | |
//poor man's pattern matching | |
switch (list) { | |
case empty(): return acc; | |
default: { | |
const { val, rest } = list; | |
return func(fold_left(func, rest, acc), val); | |
} | |
} | |
}; | |
const filter = <T>(func: (val: T) => boolean, list: List<T>): List<T> => | |
fold_left((acc: List<T>, val: T) => func(val) ? cons(val, acc) : acc, list, empty()); | |
const map = <T, N>(func: (val: T) => N, list: List<T>): List<N> => | |
fold_left((acc: List<N>, val: T) => cons(func(val), acc), list, empty()) | |
const list: List<number> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
.reduce((lst, val) => cons(val, lst), empty()); | |
const filtered_and_mapped = map(i => i.toString(), filter(i => i % 2 === 0, list)); //[] | |
const js_array = fold_left((a, i) => [...a, i], list, []); // [1,2,3,4,5] | |
const sum = fold_left((a, i) => a + i, list, 0); // 15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment