gpt4 book ai didi

generics - F# 内联函数 : instance member constraint fail

转载 作者:行者123 更新时间:2023-12-04 01:54:30 26 4
gpt4 key购买 nike

我尝试使用 member constraint和我的 inline像这样的功能:

    let inline extractMessageAsync 
(envelope: ^env when ^env:
(member GetBodyAsync: unit-> Task<'a>)) =
envelope.GetBodyAsync()

但是我得到以下错误:

Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved.

虽然我知道编译器需要更多关于这种类型的信息,但我不明白为什么,特别是因为它与 static member 一起工作得很好。 (+) 等运算符的约束或 (*)等等

最佳答案

你可以像这样写一个更短更通用的版本:

let inline GetBodyAsync x = (^a: (member GetBodyAsync: unit -> ^b) x)

现在编写 GetBodyAsync 等同于编写 fun x -> x.GetBodyAsync() 而不管方法的返回类型如何。

用法:

open System.Threading.Tasks
type A() =
member this.GetBodyAsync() = Task.FromResult 1

type B() =
member this.GetBodyAsync() = async { return 2 }

A() |> GetBodyAsync |> fun x -> x.Result // 1
B() |> GetBodyAsync |> Async.RunSynchronously // 2

关于generics - F# 内联函数 : instance member constraint fail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51303323/

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