Last active
February 15, 2017 10:24
-
-
Save gvergnaud/4f672ff80222eb2066b3c771992e61dc to your computer and use it in GitHub Desktop.
This file contains 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
/* --------------------------------------------------------------------------- * | |
Utilities for managing lists, implemented using only recursion | |
* --------------------------------------------------------------------------- */ | |
const head = ([x]) => x | |
const tail = ([x, ...rest]) => rest | |
const last = xs => xs[xs.length - 1] | |
const length = xs => xs.length | |
const drop = (n, xs) => n ? drop(n - 1, tail(xs)) : xs | |
const take = (n, [x, ...rest]) => n ? [x, ...take(n - 1, rest)] : [] | |
const reverse = ([x, ...rest]) => length(rest) ? [...reverse(rest), x] : [x] | |
const map = (f, [x, ...rest]) => length(rest) ? [f(x), ...map(f, rest)] : [f(x)] | |
const filter = (f, [x, ...rest]) => length(rest) ? f(x) ? [x, ...filter(f, rest)] : filter(f, rest) : f(x) ? [x] : [] | |
const reduce = (f, acc, [x, ...rest]) => length(rest) ? reduce(f, f(acc, x), rest) : f(acc, x) | |
const reduceRight = (f, acc, xs) => reduce(f, acc, reverse(xs)) | |
const fact = x => x ? x * fact(x - 1) : 1 | |
const compose = (...funcs) => x => reduceRight((acc, f) => f(acc), x, funcs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment