F#缺少类型约束(F# missing type constraint)

2019-10-20 23:56发布

在下面的代码,请注意get_Zero类型的约束:

type Wrapper<'t> = { Data : 't[] }

let compute<'t
    when 't : (static member get_Zero : unit -> 't)
    and 't : (static member (~-) : 't -> 't)
    and 't : (static member (+) : 't * 't -> 't)>
        (wrapper : Wrapper<'t>) =
    wrapper.Data
        |> Seq.mapi (fun i value -> (i, value))
        |> Seq.sumBy (fun (i, value) ->
            if i % 2 = 0 then value
            else -value)

尽管我已经有一个明确的类型约束,我仍然获得在调用Seq.sumBy以下编译器错误:

A型参数丢失一个约束 '时^ T:(静态成员get_Zero: - > ^ T)'

任何人都知道是怎么回事吗? 谢谢。

Answer 1:

试图让下游的静态成员的约束明确可以在挫折的锻炼,而且,幸运的是,很少有必要。 只要勾选功能inline ,让他们推断。

let inline compute (wrapper : Wrapper<_>) =
    wrapper.Data
    |> Seq.mapi (fun i value -> (i, value))
    |> Seq.sumBy (fun (i, value) ->
        if i % 2 = 0 then value
        else -value)

正确的签名是:

let inline compute<'t
            when 't : (static member Zero : 't)
            and 't : (static member (~-) : 't -> 't)
            and 't : (static member (+) : 't * 't -> 't)>

(你会注意到在错误信息的签名甚至不是有效的语法: when ^t : (static member get_Zero : -> ^t)这就是我所谓的令人沮丧的)



文章来源: F# missing type constraint