How to return from iteration by sequence?

Given the predicate "p", which says the solution is good enough. The cost function is "f", which indicates how well the possible solution is, and the function that searches for the "best" (that is, low cost) solution in the sequence of possible solutions. As an idiomatic way to cancel an estimate - in case the predicate guarantees that the current solution is "good enough" - it looks like this.

i.e. something like that:

let search pf solutionSpace = solutionSpace |> Seq.map (fun x -> fx, x) |> Seq.ignoreAllFollowingElementsWhenPredicateIsTrue (fun (c, s) -> pc) |> Seq.minBy (fun (c, _) -> c) 
+4
source share
1 answer

This is called Seq.takeWhile in F # (when the predicate returns false, stop the sequence).

Usage example:

 let search pf solutionSpace = solutionSpace |> Seq.map (fun x -> fx, x) |> Seq.takeWhile (fun (c, s) -> not (pc)) |> Seq.minBy (fun (c, _) -> c) 
+5
source

Source: https://habr.com/ru/post/1347960/


All Articles