F# missing type constraint

末鹿安然 提交于 2019-12-24 04:38:08

问题


In the following code, note the type constraint for 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)

Even though I already have an explicit type constraint, I'm still getting the following compiler error on the call to Seq.sumBy:

A type parameter is missing a constraint 'when ^t : (static member get_Zero : -> ^t)'

Anyone know what's going on here? Thanks.


回答1:


Trying to make downstream static member constraints explicit can be an exercise in frustration, and, fortunately, it's seldom necessary. Just mark the function inline and let them be inferred.

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)

The correct signature is:

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

(You'll notice the signature in the error message isn't even valid syntax: when ^t : (static member get_Zero : -> ^t). This is part of what I mean by frustrating.)



来源:https://stackoverflow.com/questions/25870540/f-missing-type-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!