Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# pattern match to a range of numbers

I have a function getFullFitness

let getFullFitness population = 
     ResizeArray(population |> Seq.map snd) |> Seq.sum

and I pattern match in the function realTick

let realTick population = 
    match(getFullfitness population) with
    |(50) -> population
    | _ -> childGeneration population

Question is on the line |(50) -> population. Since getFullFitness returns an integer sum, how do i match values between 0 and 50 in realTick?

like image 333
BBH1023 Avatar asked Nov 27 '22 03:11

BBH1023


2 Answers

One way is to use a guard -

|t when t < 50 -> ...
like image 115
John Palmer Avatar answered Dec 06 '22 07:12

John Palmer


In F#, a recommended way to pattern match on ranges is to use active patterns. If we carefully manipulate pattern names, it will look quite close to what we want:

let (|``R0..50``|_|) i =
    if i >= 0 && i <= 50 then Some() else None

let realTick population = 
    match(getFullfitness population) with
    | ``R0..50`` -> population
    | _ -> childGeneration population

Pattern matching on ranges is supported in OCaml, but it's unlikely to be added to F#. See the related User Voice request at http://fslang.uservoice.com/forums/245727-f-language/suggestions/6027309-allow-pattern-matching-on-ranges.

like image 33
pad Avatar answered Dec 06 '22 09:12

pad