F# Floating point ranges are experimental and may be deprecated

后端 未结 6 1781
猫巷女王i
猫巷女王i 2020-12-19 15:27

I\'m trying to make a little function to interpolate between two values with a given increment.

[ 1.0 .. 0.5 .. 20.0 ]

The compiler tells m

6条回答
  •  轮回少年
    2020-12-19 16:07

    Updated version of Tomas Petricek's answer, which compiles, and works for decreasing ranges (and works with units of measure): (but it doesn't look as pretty)

    let rec frange(from:float<'a>, by:float<'a>, tof:float<'a>) = 
       // (extra ' here for formatting)
       seq { 
            yield from
            if (float by > 0.) then
                if (from + by <= tof) then yield! frange(from + by, by, tof) 
            else   
                if (from + by >= tof) then yield! frange(from + by, by, tof) 
           }
    
    #r "FSharp.Powerpack"
    open Math.SI 
    frange(1.0, -0.5, -2.1)
    

    UPDATE I don't know if this is new, or if it was always possible, but I just discovered (here), that this - simpler - syntax is also possible:

    let dl = 9.5 / 11.
    let min = 21.5 + dl
    let max = 40.5 - dl
    
    let a = [ for z in min .. dl .. max -> z ]
    let b = a.Length
    

    (Watch out, there's a gotcha in this particular example :)

提交回复
热议问题