gpt4 book ai didi

generics - F#:IEnumerable> 与 list 不兼容?

转载 作者:行者123 更新时间:2023-12-02 19:52:13 26 4
gpt4 key购买 nike

所以我有以下代码,它给出了类型不匹配编译器错误,但我不知道为什么:

[<Test>]
member this.TheTest() =
let tuple = (DateTime.Now, 10)
let listOfTuples = [ tuple ]
SomeType.SomeFunc(listOfTuples)

static member SomeFunc (listOfTuples: IEnumerable<Tuple<DateTime,int>>) =
Console.WriteLine("foo")

为什么类型不兼容?

更重要的是,如何表达 SomeFunc 的签名以与调用兼容?

最佳答案

这里的实际问题是试图通过 ('a * 'b)进入一个函数取 Tuple<'a, 'b> 。虽然它们的内部表示相同,但​​ F# 编译器对两者的处理方式不同。

这在 F# language spec, section 6.3.2 中有详细说明。 :

When considered as static types, tuple types are distinct from their encoded form. However, the encoded form of tuple values and types is visible in the F# type system through runtime types.

问题在于编译器正在使用“静态类型”来查看此函数是否匹配,但根据规范,它不是匹配的。

And more importantly, how can I express SomeFunc's signature to be compatible with the call?

您可以通过多种方式解决此问题。最简单的方法是重新定义方法的类型规范以使用元组表达式:

static member SomeFunc (listOfTuples: IEnumerable<(DateTime * int)>) =
Console.WriteLine("foo")

请注意,上面的内容可以用更惯用的方式编写(具有完全相同的含义):

static member SomeFunc (listOfTuples: (DateTime * int) seq) =
Console.WriteLine("foo")

关于generics - F#:IEnumerable<Tuple<TA,TB>> 与 list<TA*TB> 不兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22567052/

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