我有以下代码:
IEnumerable<KeyValuePair<T, double>> items =
sequence.Select(item => new KeyValuePair<T, double>(item, weight(item)));
if (items.Any(pair => pair.Value<0))
throw new ArgumentException("Item weights cannot be less than zero.");
double sum = items.Sum(pair => pair.Value);
foreach (KeyValuePair<T, double> pair in items) {...}
Run Code Online (Sandbox Code Playgroud)
哪里weight是Func<T, double>.
问题是我希望weight尽可能少地执行.这意味着每件物品最多应执行一次.我可以通过将它保存到数组来实现这一点.但是,如果任何权重返回负值,我不想继续执行.
有没有办法在LINQ框架内轻松完成这项工作?
Eri*_*ert 15
当然,这是完全可行的:
public static Func<A, double> ThrowIfNegative<A, double>(this Func<A, double> f)
{
return a=>
{
double r = f(a);
// if r is NaN then this will throw.
if ( !(r >= 0.0) )
throw new Exception();
return r;
};
}
public static Func<A, R> Memoize<A, R>(this Func<A, R> f)
{
var d = new Dictionary<A, R>();
return a=>
{
R r;
if (!d.TryGetValue(a, out r))
{
r = f(a);
d.Add(a, r);
}
return r;
};
}
Run Code Online (Sandbox Code Playgroud)
现在...
Func<T, double> weight = whatever;
weight = weight.ThrowIfNegative().Memoize();
Run Code Online (Sandbox Code Playgroud)
你完成了