f# - F#度量单位,通用性问题

标签 f# units-of-measurement

(我是still banging,使用F#中的度量单位)

我在制作采用“类型化”浮点数的“通用”函数时遇到问题。

下面的模型类旨在根据因子“c”来显示位置累计错误。编译器不喜欢我在类型​​主体中说“0。<'a>”(“度量单位文字中的意外类型参数”)。

///Corrects cumulative error in position based on s and c
type Corrector(s_init:float<'a>) =
    let deltaS ds c = sin (ds / c) //incremental error function

    //mutable values
    let mutable nominal_s = s_init
    let mutable error_s = 0.<'a>  //<-- COMPILER NO LIKE

    ///Set new start pos and reset error to zero
    member sc.Reset(s) = 
        nominal_s <- s
        error_s <- 0.<'a>  //<-- COMPILER NO LIKE

    ///Pass in new pos and c to corrector, returns corrected s and current error    
    member sc.Next(s:float<'a>, c:float<'a>) = 
        let ds = s - nominal_s //distance since last request
        nominal_s <- s   //update nominal s
        error_s <- error_s + (deltaS ds c) //calculate cumulative error
        (nominal_s + error_s, error_s) //pass back tuple

我认为,另一个相关的问题仍然与“通用”功能有关。

在下面的代码中,我试图做的是创建一个函数,该函数将接受任何类型的浮点数的#seq并将其应用于仅接受“普通”浮点数的函数。第三行给出了'Value Restriction'错误,我看不到任何出路。 (删除#可解决问题,但我想避免为列表,序列,数组等写相同的东西。)
[<Measure>] type km //define a unit of measure
let someFloatFn x = x + 1.2 //this is a function which takes 'vanilla' floats
let MapSeqToNonUnitFunction (x:#seq<float<'a>>) = Seq.map (float >> someFloatFn) x
let testList = [ 1 .. 4 ] |> List.map float |> List.map ((*) 1.0<km>)
MapSeqToNonUnitFunction testList

最佳答案

您可以将第一个“不喜欢的编译器”更改为

let mutable error_s : float<'a> = 0.0<_>

而编译器似乎喜欢这样。

至于第二个问题,我没有看到与您相同的错误,这是
[<Measure>] type km 
//define a unit of measure
let someFloatFn x = x + 1.2 //this is a function which takes 'vanilla' floats
let MapSeqToNonUnitFunction (x:seq<float<_>>) = Seq.map (float >> someFloatFn) x
let testList = [ 1 .. 4 ] |> List.map float |> List.map ((*) 1.0<km>)
let testList2 = testList :> seq<_>
let result = MapSeqToNonUnitFunction testList2
printfn "%A" result

为我编译(尽管对seq <_>的up恼有点令人讨厌,但我不确定是否有简便的方法可以摆脱它)。

另外,我认为惯例是将单位参数命名为'u,'v,...而不是'a,'b,...

关于f# - F#度量单位,通用性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/460766/

相关文章:

data-structures - F# PurelyFunctionalDataStructures WeightBiasedLeftistHeap ex 3.4

f# - 计算表达式中的归零和合并

html - em是如何计算的?

F#:度量单位可以在运行时动态绑定(bind)吗?

python - GeoDjango 多边形区域

build - 如何仅在控制台上在 Linux 上构建 FSharp 程序?

f# - 空隙与单位相反

c# - UICollectionViewCell 定义 F#

f# - F#中的度量单位的分数幂

python - 两个英制长度之差