问题描述
|
给定一个谓词“ p”,它表明一个解决方案是否足够好。成本函数“ f”,说明可能的解决方案有多好,该函数在一系列可能的解决方案中搜索“最佳”(即最低成本)解决方案。在谓词确保当前解决方案“足够好”的情况下,惯用方式如何取消评估-看起来像。
即像这样的东西:
let search p f solutionSpace =
solutionSpace |> Seq.map (fun x -> f x,x)
|> Seq.ignoreAllFollowingElementsWhenPredicateIsTrue (fun (c,s) -> p c)
|> Seq.minBy (fun (c,_) -> c)
解决方法
这在F#中称为
Seq.takeWhile
(当谓词返回false时,停止序列)。
使用示例:
let search p f solutionSpace =
solutionSpace |> Seq.map (fun x -> f x,x)
|> Seq.takeWhile (fun (c,s) -> not (p c))
|> Seq.minBy (fun (c,_) -> c)