Skip to content

Instantly share code, notes, and snippets.

@davidchase
Last active December 19, 2016 05:05
Show Gist options
  • Save davidchase/319b75d4fa54c11ff3a55ee400811a71 to your computer and use it in GitHub Desktop.
Save davidchase/319b75d4fa54c11ff3a55ee400811a71 to your computer and use it in GitHub Desktop.
// @TODO pull out the mapping and filtering
// make composable/lazy(only run when fold'ing)
const copyList = xs => reduce(concat, [], xs)
const filterR = (f, xs) => reduce((acc, x) => f(x) ? acc.concat(x) : acc , [], xs)
const mapR = (f, xs) => reduce((acc, x) => acc.concat(f(x)), [], xs)
// List with methods in terms of reduce
const List = xs => ({
xs,
map: f => List(mapR(f, xs)),
fold: (empty = []) => xs.reduce((acc, x) => acc.concat(identity(x)), empty),
chain: f => List(xs.reduce((acc, x) => acc.concat(f(x).xs), [])),
ap: list => List(xs.reduce((acc, f) => acc.concat(map(f, list.xs)), [])),
concat: list => List(concat(xs, list.xs)),
filter: f => List(filterR(f, xs)),
toString: () => `List [${xs}]`
})
List.of = (...args) => List(args)
List.empty = () => List([])
List.map = (f, xs) => xs.map(f)
List.chain = (f, xs) => xs.chain(f)
List.ap = (uf, ux) => uf.ap(ux)
// Alternative List
// map + ap derived from chain
const ListA = xs => ({
xs,
chain: f => ListA(xs.reduce((acc, x) => acc.concat(f(x).xs), [])),
map: f => ListA(xs).chain(x => ListA.of(f(x))),
ap: uf => ListA(xs).chain(f => ListA(uf.xs).map(f)),
toString: () => `ListA [${xs}]`
})
ListA.of = (...args) => ListA(args)
List([1,2,3,4,5]).filter(x => x > 3).map(inc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment