如何从序列的迭代中提前返回?

Ale*_*sti 4 f# sequences escaping seq

给定谓词"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)
Run Code Online (Sandbox Code Playgroud)

Lau*_*ent 5

Seq.takeWhile在F#中调用(当谓词返回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)
Run Code Online (Sandbox Code Playgroud)