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

How to work with mutable lists in F#?

提问人:Eben Kadile 提问时间:10/18/2017 更新时间:10/18/2017 访问量:328

问:

我是 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

编译器对一些事情感到不安:它说没有构造函数 ,它说 和 没有定义。我在 Microsoft 文档中找到了这些方法。本教程提到了 ,但它使用 而不是 ,这也不起作用。List<int>List<List<int>>InsertRemoveAtRemoveAtAddInsert

列表 f# 可变

评论


答:

8赞 Fyodor Soikin 10/18/2017 #1

在 F# 中,类型是不可变的 F# 列表。它与 不同,这是您链接的文档中描述的内容。List<'t>System.Collections.Generic.List<T>

要访问后者,请打开命名空间(但要注意:这将掩盖常规 F# 列表),或者通过其 F# 别名引用它,这也更好地表达了它的真实性质。System.Collections.GenericResizeArray<'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

(另请注意,它不是CountLength)