gpt4 book ai didi

f# - 这是 F# 错误吗?

转载 作者:行者123 更新时间:2023-12-02 07:50:57 24 4
gpt4 key购买 nike

我有一个正在实现 IEnumerable<T> 的类型界面,一切正常:

open System

type Bar() =

interface Collections.IEnumerable with
member x.GetEnumerator () = null

interface Collections.Generic.IEnumerable<int> with
member x.GetEnumerator () = null

但是如果类型继承 IEnumerable 就会出错通过基类型实现接口(interface):

open System

type Foo() =
interface Collections.IEnumerable with
member x.GetEnumerator () = null

type Bar() =
inherit Foo()

interface Collections.Generic.IEnumerable<int> with
member x.GetEnumerator () = null

上面的代码会产生类型推断错误:

  • The member 'GetEnumerator<'a0 when 'a0 : null> : unit -> 'a0 when 'a0 : null' does not have the correct type to override any given virtual method

  • The member 'GetEnumerator<'a0 when 'a0 : null> : unit -> 'a0 when 'a0 : null' does not have the correct number of method type parameters. The required signature is 'GetEnumerator : unit -> Collections.Generic.IEnumerator<int>'.

是我做错了什么还是 F# 编译器错误?

Microsoft (R) F# 2.0 Interactive build 4.0.30319.1


更新更规范的例子:

type IFoo     = abstract Bar : obj list
type IFoo<'a> = abstract Bar : 'a list
inherit IFoo
/* ok */
type Foo = interface IFoo with member x.Bar = []
interface IFoo<Foo> with member x.Bar = []
/* fail */
type FooBase = interface IFoo with member x.Bar = []
type FooDerived = interface IFoo<Foo> with member x.Bar = [] // <---
inherit FooBase
/*
error FS0017: The member 'get_Bar : unit -> 'a list' does not
have the correct type to override any given virtual method.
*/

最佳答案

编译器无法从您的“空”实现中推断出正确的类型。尝试

open System

type Foo() =
interface Collections.IEnumerable with
member x.GetEnumerator () = null

type Bar() =
inherit Foo()

interface Collections.Generic.IEnumerable<int> with
member x.GetEnumerator () : Collections.Generic.IEnumerator<int> = null

更新:
原因是 GetEnumerator 的类型Bar 实现的方法类型不明确为 IEnumerable<'a>实现/继承非泛型 IEnumerable它还指定了一个(非通用)GetEnumerator方法。那么,编译器应该如何推断,如果他得到的都是空值,你到底在尝试实现哪个方法?因此在这种情况下我们需要一个类型注释。

关于f# - 这是 F# 错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3856162/

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