如何在F#中使用可变列表?

Ebe*_*ley 2 f# list mutable

我是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
Run Code Online (Sandbox Code Playgroud)

编译器是苦恼的几件事情:它说没有任何构造函数List<int>,List<List<int>>和它说,InsertRemoveAt没有定义.我在microsoft docs中找到了这些方法.本教程提到RemoveAt,但它使用Add而不是Insert,也没用.

Fyo*_*kin 5

在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
Run Code Online (Sandbox Code Playgroud)

(还要注意Count,不是Length)