下面給出了我正在嘗試做的簡化案例。
鑒于此記錄型別:
type Attribute<'TName,'TOther> =
{
Name:'TName
Data:'TOther
}
我想定義一個帶有函式的介面,該函式將忽略 Attribute 型別的第二個型別引數,并且僅在第一個型別引數的基礎上進行操作。如:
type AttributeMapper =
interface
abstract member atrName<'a> : Attribute<'a, _> -> 'a
end
這給了我:
...: [FS0715] Anonymous type variables are not permitted in this declaration'
如果我將型別引數提升為 Interface 的型別,那么編譯器會很高興。這里沒有問題:
type AttributeProcessor2<'a> =
interface
abstract member atrName: Attribute<'a, _> -> 'a
end
let atrMapperInstance2 =
{new AttributeProcessor2<_> with
member _.atrName (x:Attribute<string, _>) = x.Name }
我想了解這兩種情況之間的區別,以及為什么我不允許在第一種情況下使用通配符。
uj5u.com熱心網友回復:
我認為簡短的回答是您可以選擇:
- 顯式宣告成員的所有型別引數,或
- 不宣告成員的任何型別引數,這讓編譯器改為推斷它們
所以第一個atrName是非法的,因為你已經明確宣告它采用一個型別引數,而實際上它需要兩個。請注意,即使您為第二個型別引數指定了名稱,這仍然是非法的:
type AttributeMapper =
interface
abstract member atrName<'a> : Attribute<'a, 'b> -> 'a // error FS0039: The type parameter 'b is not defined.
end
另一方面,第二個atrName是合法的,因為編譯器可以推斷它只接受一個型別引數,所以它等價于:
type AttributeProcessor2<'a> =
interface
abstract member atrName<'b> : Attribute<'a, 'b> -> 'a
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/363420.html
