如何使用F#中的可变列表?
问题描述:
我是F#的新手,我正在制作一个程序,需要找到某个列表的给定长度的每个子列表。我不确定如何去解决这个问题,所以我阅读this question并决定将答案移植到F#。下面是我有:如何使用F#中的可变列表?
let rec getSubLists (len : int) (list : List<int>) : List<List<int>> =
let result = new List<List<int>>()
let current = new List<int>()
let rec findSubLists (len : int) (superSet : List<int>) (current : List<int>) (soln : List<List<int>>) (idx : int) : unit =
if current.Length = len then soln.Insert(len - 1, current)
elif idx = superSet.Length then
let x = superSet.[idx]
current.Insert(len, x)
findSubLists len superSet current soln (idx + 1)
current.RemoveAt(x)
findSubLists len superSet current soln (idx + 1)
else()
findSubLists len list current result 0
result
编译器是苦恼的几件事情:它说没有构造函数List<int>
,List<List<int>>
,和它说,Insert
和RemoveAt
没有定义。我在microsoft docs中发现了这些方法。 This tutorial提到RemoveAt
,但它使用Add
而不是Insert
,这也不起作用。
答
在F#中,类型List<'t>
是不可变的F#列表。它与System.Collections.Generic.List<T>
不同,这是您链接的文档中描述的内容。要访问后者,可以打开System.Collections.Generic
命名空间(但要小心:这会影响常规F#列表),也可以通过其F#别名ResizeArray<'t>
引用它,这也更好地表达了它的真实性质。
let rec getSubLists (len : int) (list : ResizeArray<int>) : ResizeArray<ResizeArray<int>> =
let result = new ResizeArray<ResizeArray<int>>()
let current = new ResizeArray<int>()
let rec findSubLists (len : int) (superSet : ResizeArray<int>) (current : ResizeArray<int>) (soln : ResizeArray<ResizeArray<int>>) (idx : int) : unit =
if current.Count = len then soln.Insert(len - 1, current)
elif idx = superSet.Count then
let x = superSet.[idx]
current.Insert(len, x)
findSubLists len superSet current soln (idx + 1)
current.RemoveAt(x)
findSubLists len superSet current soln (idx + 1)
else()
findSubLists len list current result 0
result
(也注意到,它的Count
,不Length
)