Created
March 8, 2015 04:29
-
-
Save TGOlson/e5a9fb1cfcc166ccfa73 to your computer and use it in GitHub Desktop.
Single set list comprehension in JavaScript
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
| var R = require('ramda'); | |
| // flipped filter to work with folds -> (acc, fn) | |
| // [a] -> [(a -> Boolean)] -> [a] | |
| var reduceWithFilter = R.reduce(R.flip(R.filter)); | |
| // (a -> b) -> [a] -> [(a -> Boolean)] -> [a] | |
| function listComp(outputFn, inputSet, predicates) { | |
| return R.compose(R.map(outputFn), reduceWithFilter(inputSet))(predicates); | |
| } | |
| var double = R.multiply(2); | |
| var gtWith = function(p, n) { | |
| return R.converge(R.gt, p, R.always(n)); | |
| }; | |
| var odd = R.compose(R.eq(1), R.modulo(R.__, 2)); | |
| var set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
| // Haskell list comprehension | |
| // double x = x + x | |
| // [double x | x <- [1..10], double x > 12] | |
| // [14,16,18,20] | |
| listComp(double, set, [gtWith(double, 12)]); | |
| // => [ 14, 16, 18, 20 ] | |
| // works with multiple predicates | |
| listComp(double, set, [odd, gtWith(double, 12)]); | |
| // => [ 14, 18 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment