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

发布于 2024-09-11 22:51:53 字数 266 浏览 3 评论 0 原文

为什么这段代码不起作用?

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>>'

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>>'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伴随着你 2024-09-18 22:51:53

将代码更改为

type Test() = 
  static member func (a: seq<#seq<'a>>) = 5. 

let a = [[4.]] 
Test.func(a) 

技巧在于 a 的类型。您需要明确允许外部 seq 保存 seq<'a> 的实例。 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. You need to explicitly allow the outer seq to hold instances of seq<'a> and subtypes of seq<'a>. Using the # symbol enables this.

暖风昔人 2024-09-18 22:51:53

错误消息描述了问题 - 在 F# 中,list>seq> 不兼容。

upcast 函数通过将 a 转换为 list> 来帮助解决这个问题,然后与 兼容>seq>:

let a = [upcast [4.]]
Test.func(a)

编辑: 您可以使 func 在其接受的类型方面更加灵活。原始版本仅接受 seq<'a> 序列。尽管 list<'a> 实现了 seq<'a>,但类型并不相同,编译器会给出错误。

但是,您可以修改 func 以接受任何类型的序列,只要该类型实现 seq<'a>,只需将内部类型编写为 #seq

type Test() =
  static member func (a: seq<#seq<'a>>) = 5.

let a = [[4.]]
Test.func(a) // works

The error message describes the problem -- in F#, list<list<'a>> isn't compatible with 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>>:

let a = [upcast [4.]]
Test.func(a)

Edit: You can make func more flexible in the types it accepts. The original accepts only sequences of seq<'a>. Even though list<'a> implements seq<'a>, the types aren't identical, and the compiler gives you an error.

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:

type Test() =
  static member func (a: seq<#seq<'a>>) = 5.

let a = [[4.]]
Test.func(a) // works
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文