F#缺少类型约束 [英] F# missing type constraint

查看:166
本文介绍了F#缺少类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

即使我已经具有显式类型约束,但在调用Seq.sumBy时仍然遇到以下编译器错误:

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

当^ t时,类型参数缺少约束'(静态成员 get_Zero:-> ^ t)'

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

有人知道这是怎么回事吗?谢谢.

Anyone know what's going on here? Thanks.

推荐答案

尝试使下游静态成员约束明确化可能是一个令人沮丧的练习,幸运的是,它几乎没有必要.只需标记功能inline并进行推断即可.

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)

正确的签名是:

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).这是我令人沮丧的一部分.)

(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.)

这篇关于F#缺少类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆