f#类型约束可索引



我正在尝试创建一个应该代表"切片"的类型。

我知道f#中有一些类似的类型,但没有一个指定了我需要的标准。

要做到这一点,它需要携带对类型'content '集合的引用,并且该内容需要是可索引的。所以我尝试了这个约束,因为一个类型只需要有成员Item (get/set),所以我尝试了这个
type Slice<'a, 'content when 'content: (member Item: int -> 'a)>

这仍然抛出通常的错误

所以有可能约束类型仍然是通用的,但约束是可索引的吗?

我认为这样的东西应该工作:

type Slice<'a, 'content when 'content: (member get_Item: int -> 'a)> =
{
Content : 'content
Start : int
Stop : int
}
with
member inline slice.get_Item(i) =
slice.Content.get_Item(slice.Start + i)

我也在Slice上实现了get_Item,所以你可以取一片的一片。下面是一些这种类型的值:

let strSlice =
{
Content = "hello"
Start = 1
Stop = 2
}
let arraySlice =
{
Content = [| 2; 4; 6; 8 |]
Start = 0
Stop = 3
}
let strSliceSlice =
{
Content = strSlice
Start = 0
Stop = 1
}
[<Interface>]
type Indexable<'a> =
abstract member Item: int -> 'a with get
[<Struct>]
type Slice<'a> =
{
content: Indexable<'a>
start: int
len: int
}
with
interface Indexable<'a> with
member I.Item with get(i) = I.[idx]
member S.Item with get(idx) = 
if idx >= S.len 
then raise(IndexOutOfRangeException()) 
else S.content.[S.start+idx]

这工作。

最新更新