Skip to content

Instantly share code, notes, and snippets.

@scott-christopher
Created May 6, 2015 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scott-christopher/598c9cf3a1cd4dd8c034 to your computer and use it in GitHub Desktop.
Save scott-christopher/598c9cf3a1cd4dd8c034 to your computer and use it in GitHub Desktop.
Right fold with the accumulated value wrapped in a thunk, allowing short-circuiting
var R = require('ramda');
// :: ((a, () -> b) -> b) -> b -> List[a] -> b
function foldRThunk(fn, acc, list) {
return R.isEmpty(list) ? acc : fn(
list[0],
function () { return foldRThunk(fn, acc, R.tail(list)) }
);
}
// :: (a -> Boolean) -> List[a] -> Boolean
function exists(p, list) {
return foldRThunk(function(a, b) {
return p(a) || b()
}, false, list);
}
console.log(exists(R.eq(4), [2,4,6,8])); //=> true
console.log(exists(R.eq(4), [1,3,5,7])); //=> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment