-
-
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
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
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