2D列表的递归函数

  • 本文关键字:递归函数 列表 2D f#
  • 更新时间 :
  • 英文 :


我对f#很陌生,所以请原谅我的无知。我有一个int的2D列表。我正在尝试制作一个函数,该函数将返回另一个2D列表,该列表将只包含最低尾部项目。类似这样的东西:

[[2, 3]
[2, 4]
[2, 5]              [[2, 3]
[3, 8]      =>       [3, 2]
[3, 6]               [4, 1]]
[3, 2]
[4, 1]]

我可以用找到1D列表的最小值

let findMin items = 
match items with
| [] -> ()
| head :: tail ->
let rec recMin minSoFar items =
match items with
| [] -> minSoFar
| head :: tail ->
if head < minSoFar then
recMin head tail
else
recMin minSoFar tail
recMin head tail

这是我从这个答案中抄来的。如有任何帮助,我们将不胜感激。

您谈论的是2D列表,但您的示例输入实际上是元组列表的列表(其中每个列表只包含一个元组值(。我认为这是一个拼写错误,您想写;而不是;,并创建一个实际的2D列表:

let input = 
[ [2;  3]
[2;  4]
[2;  5]  
[3;  8]  
[3;  6]  
[3;  2]
[4;  1] ]

现在,作为结果,您想要得到的三个项目似乎是列表中最后一个元素最小的三个子列表。获得这些信息的最简单方法是根据子列表的最后一个元素对列表进行排序,然后取前3名:

input 
|> List.sortBy List.last
|> List.take 3  

这将返回所需的三个子列表,但不按原始顺序返回。如果你想按原始顺序排列,那么你可以先找到倒数第三小的元素,然后用它来过滤原始列表:

let last = 
input 
|> List.map List.last
|> List.sort
|> List.item 2
input 
|> List.filter (fun l -> List.last l <= last)

请注意,我的代码不能正确处理小于3的输入或空列表等情况,但它应该能让您了解解决此问题的一种方法。

最新更新