繁体   English   中英

为什么我在 class 未定义的参数中收到错误提示 function - 错误 FS0039:值或构造函数“函数”未定义

[英]Why I get error saying function in argument for a class not defined - error FS0039: The value or constructor 'function' is not defined

我有一个 class 叫做'car',它可以实例化对象。

type car (fuelEco: float,fuel:int) =
    let mutable fuelEco = fuelEco
    let mutable tank = 0
    member this.addGas (liter: int) = tank <- liter
    member this.gasLeft () = tank
    member this.drive (km: int) =
        if float(km) > (float(tank) * fuelEco) then raise (InsuficientGas "You can't drive this far - you have insuficient amount of gas")
        else tank <- tank - int((float(km) / fuelEco))

我有另一个 class 称为“Assert”(大写字母),它断言了给 class Assert 的编号 arguments。

type Assert (str: string, a:'a, b: 'b,f:('a -> 'a -> bool)) =
    static member test = 
        if (f a (int(b))) then 
            printfn "%A : %A" "Pass" str
        else printfn "%A : %A" "Pass" str

然后我必须通过以下代码测试断言:

let fe = 18.3
let mini = new car(fe,0)
Assert.test "GasLeft () - Full?" (mini.gasLeft ()) 10.0 (=)
Assert.test "GasLeft () - Empty?" (mini.gasLeft ()) 0 (=)

对于第一个测试,我希望得到“失败”:“GasLeft () - Full?” 对于第二次测试,我希望得到“通过”:“GasLeft() - Empty?” 当给出指定的 arguments 时。

但是,F# 告诉我 f 没有在 arguments 中定义。调用 Assert.test 时我的 f 是 (=),根据 F# 采用 ('a -> 'a -> bool)。 请注意,我将 b 转换为 int,因为它可以作为 float 类型给出,所以可以肯定的是,我比较两个整数,我首先将它转换为 int。

所以我不明白为什么它说 f 未定义?

问题出在您的Assert class 上。arguments 将进入 class 构造函数而不是 static 成员。 static 成员无权访问 class 的 state,因此您会收到错误消息。

我通过将 arguments 移动到test成员来解决此问题,并将它们从元组 arguments(逗号分隔)更改为 curried arguments(空格分隔),以便可以像您一样以 curried 样式调用它们。

type Assert =
    static member test (str: string) (a:'a) (b: 'b) (f:('a -> 'a -> bool)) = 
        if (f a (int(b))) then 
            printfn "%A : %A" "Pass" str
        else printfn "%A : %A" "Pass" str

浮点数和整数似乎有些危险的混合。 我建议把这里所有的数字类型都改成float,这样应该可以让代码更简单更正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM