简体   繁体   中英

Has F# anything like Haskell's where clause?

I was wondering if there is anything in F# like Haskell's where clause. It would permit to transform the following code

let roulleteWheel numberGenerator (scoredPopulation:ScoredPopulation) =
  let targetScore =
    let totalScore = totalPopulationFitness scoredPopulation
    Seq.head (numberGenerator 0.0 totalScore)

  let isMatch (score, accumulatedScore) =
    if (accumulatedScore >= targetScore) then
      Some(score)
    else
      None

  let accumulatedScores =
    let scores = Seq.map (fun (_, score) -> score) scoredPopulation
    Seq.skip 1 (Seq.scan (+) 0.0 scores)

  Seq.pick isMatch (Seq.zip scoredPopulation accumulatedScores)

into the (imo) slightly more readable version

let roulleteWheel numberGenerator (scoredPopulation:ScoredPopulation) =
  Seq.pick isMatch (Seq.zip scoredPopulation accumulatedScores)
  where
    let targetScore =
      let totalScore = totalPopulationFitness scoredPopulation
      Seq.head (numberGenerator 0.0 totalScore)

    let isMatch (score, accumulatedScore) =
      if (accumulatedScore >= targetScore) then
        Some(score)
      else
        None

    let accumulatedScores =
      let scores = Seq.map (fun (_, score) -> score) scoredPopulation
      Seq.skip 1 (Seq.scan (+) 0.0 scores)

as it shows up the core part of the function first and the implementation details later (nitpicking, I reckon!).

My guess is that it wouldn't be possible by the way F# parses the code files. Am I right? Looking at F#'s keywords reference doesn't seem to show off anything like I'm looking for. If it doesn't exist, is there any other way to better factor out the code shown? I'd say it is ok as it is, but you never know..

Sadly no - even more sadly order in F# matters a lot. You can use mutual recursive let rec ... and ... but it's just not the same as where.

There isn't any such keyword in F#. The difference in both the code is that in one the definition comes first and then usage and in the 2nd one it is vice-versa.

最近版本的F#中的“in”关键字不是类似于Haskell的“where”子句吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM