1

我已经编写了一个函数并开始对其进行重构,但是我遇到了一些问题,即“无法根据此程序点之前的类型信息确定方法 'Round' 的唯一重载”。错误,但我不明白为什么。

let CheckValuesLin (lowValue, highValue) multiplier (sigFigs:int) =
    let arithmean (lowValue, highValue) =
        (lowValue + highValue) / 2.0
    let createRangeValue numberModifier meanfunction= 
        let mean = meanfunction (lowValue, highValue)
        let rangeValue = mean + (numberModifier mean) * multiplier
        Math.Round(rangeValue, sigFigs)
    let createRangeValues valueCreatingFunction=
        (createRangeValue makeNegative arithmean, createRangeValue keepPositive arithmean)
    let greatestMinValue, lowestMaxValue = createRangeValues createRangeValue
    (greatestMinValue, lowestMaxValue)

失败的线是 Math.Round 线,当我设置rangerange: float. 这让我感到困惑,因为我悬停的所有内容似乎已经推断出正确的类型,包括范围和平均值。

我不介意输入类型提示,我只想知道它为什么会失败。

4

1 回答 1

2

问题是 F# 类型推断严格从左到右,从上到下。

createRangeValue函数中,编译器只能推断所有值都是数字,没有什么强制类型为float.

虽然arithmean稍后调用似乎会给出一些浮点类型的值,但这发生在调用之后Round,因此编译器无法推断类型。

编辑更多细节:本质上编译器会看到这个:

let lowValue = 0.0 //I am being genrous by making this have a type
let highValue = 0.0
let sigFigs = 0 //this type is known
let createRangeValue (numberModifier) (meanfunction) multiplier= 
    let mean = meanfunction (lowValue, highValue)    
    let rangeValue = mean + (numberModifier mean) * multiplier
    Math.Round(rangeValue, sigFigs)

在这种情况下,rangeValue可以是其中一个floatDecimal两者都满足所有存在的约束。

对我来说,这很好用

open System
let makeNegative a = -a
let keepPositive a = a
let CheckValuesLin (lowValue, highValue) multiplier (sigFigs:int) =
    let arithmean (lowValue, highValue) =
        (lowValue + highValue) / 2.0
    let createRangeValue numberModifier (meanfunction: float * float -> float)= 
        let mean = meanfunction (lowValue, highValue)
        let rangeValue = mean + (numberModifier mean) * multiplier
        Math.Round(rangeValue, sigFigs)
    let createRangeValues valueCreatingFunction=
        (createRangeValue makeNegative arithmean, createRangeValue keepPositive arithmean)
    let greatestMinValue, lowestMaxValue = createRangeValues createRangeValue
    (greatestMinValue, lowestMaxValue)
于 2013-06-28T09:36:27.650 回答