如果 Eager 评价没问题,你可以把你的根收集到一个数组中,roots.filter(isinvalid)
用来取出无效的;然后只需使用结果数组中的第一项。
如果您需要惰性求值,您可以将其推广为一个函数,该函数对数组中的函数进行惰性求值,直到找到非空结果:
// call fn on items in arr until fn returns non-null
// returns [item, result]
// if result===false, no true value was returned
function firstNotNull(fn, arr) {
var i, length, item, result=null;
for (i = 0, length=arr.length; i < length; i++) {
item = arr[i];
result = fn(item);
if (result!==null) {
break;
}
}
return [item, result];
}
function rootComputations(root) {
var computationResult = null;
if (root==1) {
computationResult = 1;
}
return computationResult;
}
function computeRoots() {
return [0,1];
}
function foo() {
var velocity, roots, root, result, computations;
for (velocity = 0; velocity < 100; velocity++) {
roots = computeRoots();
computations = firstNotNull(rootComputations, roots);
console.log(computations);
root = computations[0];
result = computations[1];
}
}
foo();
firstNotNull()
您可以进一步概括:
// call fn on items in arr until cond(fn(item)) returns true
// returns [item, fn(item)], or null if unsatisfied
function firstSatisfying(cond, fn, arr) {
var i, length, item, fnitem, result=null;
for (i = 0, length=arr.length; i < length; i++) {
item = arr[i];
fnitem = fn(item);
if (cond(fnitem)) {
result = [item, fnitem];
break;
}
}
return result;
}
var firstNotNull = firstSatisfying.bind(null, function(item){return item!==null;});
您现在有了一个通用函数,用于获取满足您想要的任何条件的事物列表中的第一个。
ECMAScript 5 添加了许多方法,使得在数组上的急切函数式应用程序变得更加容易,但是 Javascript 没有任何用于惰性求值的本机工具。如果这是您认为您经常需要的东西,请考虑使用stream.js,它提供了一种“流”数据类型以及用于部分应用的方法。使用 stream.js,您的逻辑将如下所示:
// rootStream should be a function which returns a Stream
// It should construct a stream with the first root produced
// and a function that returns the remaining roots.
// Since I don't know how you get your roots, I'll use a stupid example:
function rootStream() {
return new Stream(0, function(){
return new Stream(1);
});
}
function isvalid(root) {
return root===1;
}
Stream.range(0,100)
.walk(function(v){
//v doesn't seem to be used?
var firstvalid = rootStream().filter(isvalid).head();
console.log(firstvalid);
});