[英]Seq seq type as a member parameter in F#
why does not this code work? 为什么这段代码不起作用?
type Test() =
static member func (a: seq<'a seq>) = 5.
let a = [[4.]]
Test.func(a)
It gives following error: 它给出以下错误:
The type 'float list list' is not compatible with the type 'seq<seq<'a>>'
Change your code to 将您的代码更改为
type Test() =
static member func (a: seq<#seq<'a>>) = 5.
let a = [[4.]]
Test.func(a)
The trick is in the type of a. 诀窍在于a的类型。 You need to explicitly allow the outer seq to hold instances of seq<'a> and subtypes of seq<'a>.
您需要明确允许外SEQ持有序列的情况下,<“一个> 和 SEQ亚型<”一个>。 Using the # symbol enables this.
使用#符号启用此功能。
The error message describes the problem -- in F#, list<list<'a>>
isn't compatible with seq<seq<'a>>
. 错误消息描述了问题 - 在F#中,
list<list<'a>>
与seq<seq<'a>>
不兼容。
The upcast
function helps get around this, by making a
into a list<seq<float>>
, which is then compatible with seq<seq<float>>
: upcast
函数通过将a
list<seq<float>>
,然后与seq<seq<float>>
兼容来帮助解决这个问题:
let a = [upcast [4.]]
Test.func(a)
Edit: You can make func
more flexible in the types it accepts. 编辑:您可以使
func
在其接受的类型中更灵活。 The original accepts only sequences of seq<'a>
. 原文只接受
seq<'a>
序列。 Even though list<'a>
implements seq<'a>
, the types aren't identical, and the compiler gives you an error. 即使
list<'a>
实现seq<'a>
,类型也不相同,编译器会给你一个错误。
However, you can modify func
to accept sequences of any type, as long as that type implements seq<'a>
, by writing the inner type as #seq
: 但是,您可以修改
func
以接受任何类型的序列,只要该类型通过将内部类型写为#seq
实现seq<'a>
:
type Test() =
static member func (a: seq<#seq<'a>>) = 5.
let a = [[4.]]
Test.func(a) // works
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.