Last active
July 21, 2017 01:25
-
-
Save mofas/93d1b94eed0aa51dfaef9567a96b79b7 to your computer and use it in GitHub Desktop.
FP data structure: map
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
const cons = (a, b) => p => p ? a : b; | |
const car = pair => pair(1); | |
const cdr = pair => pair(0); | |
const shift = xs => x => cons(x, xs); | |
const length = xs => typeof xs === 'function' ? 1 + length(cdr(xs)) : 0; | |
const get = xs => index => index ? get(cdr(xs))(index - 1) : xs; | |
const list1 = cons(1, cons(2, 3)); | |
car(list1); | |
car(cdr(list1)); | |
length(list1); | |
const list2 = shift(list1)(0); | |
car(list2); | |
length(list2); | |
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
const map = () => null; | |
const set = map => (key, value) => q => q === key ? value: map | |
const get = map => key => typeof map === 'function' ? get(map(key))(key) : map; | |
const map1 = set(map)('key1', 1); | |
get(map1)('key1') | |
get(map1)('key2') | |
const map2 = set(map1)('key2', 2) | |
get(map2)('key1') | |
get(map2)('key2') | |
const map3 = set(map2)('key1', 3) | |
get(map3)('key1') | |
get(map3)('key2') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment