gpt4 book ai didi

F# 缺少类型约束

转载 作者:行者123 更新时间:2023-12-01 05:17:22 25 4
gpt4 key购买 nike

在下面的代码中,注意 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 type parameter is missing a constraint 'when ^t : (static member get_Zero : -> ^t)'

有人知道这里发生了什么吗?谢谢。

最佳答案

尝试使下游静态成员约束显式化可能会令人沮丧,幸运的是,很少有必要这样做。只需将函数标记为 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# 缺少类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25870540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com