Last active
July 30, 2019 17:44
-
-
Save kdridi/eac34978b7179583bf74f604f38e254e to your computer and use it in GitHub Desktop.
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 compose = (g) => (f) => (x) => g(f(x)) | |
const flip = (f) => (a) => (b) => f(b)(a) | |
const rec = (f) => (...args) => f((...args) => rec(f)(...args), ...args) | |
const listCons = (x) => (y) => (m) => m(x)(y) | |
const listHead = (z) => z((p) => (_) => p) | |
const listTail = (z) => z((_) => (q) => q) | |
const listCase = (f) => (n) => (z) => (z === null ? n : f(listHead(z))(listTail(z))) | |
const map = (f) => listCase((h) => (t) => listCons(f(h))(map(f)(t)))(null) | |
const reduce = (f) => (n) => listCase((h) => (t) => reduce(f)(f(n)(h))(t))(n) | |
const filter = (f) => listCase((h) => (t) => ((r) => (f(h) ? listCons(h)(r) : r))(filter(f)(t)))(null) | |
const length = reduce((a) => (_) => a + 1)(0) | |
const empty = listCase((_) => (_) => false)(true) | |
const reverse = reduce(flip(listCons))(null) | |
const intersperse = (sep) => listCase((x) => (xs) => listCons(x)(rec((prependToAll, sep) => listCase((x) => (xs) => listCons(sep)(listCons(x)(prependToAll(sep)(xs))))(null))(sep)(xs)))(null) | |
const toString = compose((str) => (str === '' ? 'null' : `(list ${str})`))(compose(reduce((res) => (acc) => `${res}${acc}`)(''))(compose(intersperse(' '))(map((x) => `${x}`)))) | |
const fromArray = (arr) => arr.reverse().reduce((res, elm) => listCons(elm)(res), null) | |
const data = fromArray(new Array(10).fill().map((_, n) => n)) | |
length(data) | |
toString(map((n) => `[${n}]`)(data)) | |
toString(filter((n) => n % 2 === 0)(data)) | |
length(filter((n) => n % 2 !== 0)(data)) | |
empty(data) | |
toString(reverse(data)) | |
toString(fromArray([])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment