简体   繁体   English

Seq seq类型作为F#中的成员参数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM