为什么这段代码不起作用?
type Test() =
static member func (a: seq<'a seq>) = 5.
let a = [[4.]]
Test.func(a)
它给出以下错误:
The type 'float list list' is not compatible with the type 'seq<seq<'a>>'
为什么这段代码不起作用?
type Test() =
static member func (a: seq<'a seq>) = 5.
let a = [[4.]]
Test.func(a)
它给出以下错误:
The type 'float list list' is not compatible with the type 'seq<seq<'a>>'
将您的代码更改为
type Test() =
static member func (a: seq<#seq<'a>>) = 5.
let a = [[4.]]
Test.func(a)
诀窍在于 a 的类型。您需要明确允许外部 seq 保存 seq<'a> 的实例和 seq<'a> 的子类型。使用# 符号可以实现这一点。
错误消息描述了问题 - 在 F# 中,list<list<'a>>
与seq<seq<'a>>
.
该函数通过将其制成 aupcast
来帮助解决此问题,然后它与 兼容:a
list<seq<float>>
seq<seq<float>>
let a = [upcast [4.]]
Test.func(a)
编辑:您可以使其func
接受的类型更加灵活。原版只接受seq<'a>
. 即使list<'a>
implements seq<'a>
,类型也不相同,编译器会给你一个错误。
但是,您可以修改func
以接受任何类型的序列,只要该类型实现seq<'a>
,通过将内部类型编写为#seq
:
type Test() =
static member func (a: seq<#seq<'a>>) = 5.
let a = [[4.]]
Test.func(a) // works