Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 382
devoured elysium Avatar asked Sep 04 '11 11:09

devoured elysium


2 Answers

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.

like image 136
Random Dev Avatar answered Nov 09 '22 14:11

Random Dev


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.

like image 1
Ankur Avatar answered Nov 09 '22 15:11

Ankur