4

Given a predicate "p", that tells if a solution is good enough. A cost function "f" that tells how good a possible solution is and a function that searches for the "best" (i.e. lowest cost) solution in a sequence of possible solutions. How does an idiomatic way to cancel the evaluation - in case the predicate ensures that the current solution is "good enough" - look like.

i.e. something like that:

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)
Alexander Battisti
  • 2,178
  • 2
  • 19
  • 24

1 Answers1

5

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

Example of use:

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)
Laurent
  • 2,951
  • 16
  • 19