试图学习F#...排序整数列表

Dan*_*nny 2 python sorting f#

我在过去的几个月里一直在使用Python,现在我试图给F#一个旋转.只有......我真的不明白.我一直在阅读过去几天的文档,但仍然不完全了解如何完成基本任务.

我一直在关注tryfsharp.org和fsharp.net上的教程.

例如,如何在F#中完成用Python编写的这个基本任务?

unsorted = [82, 9, 15, 8, 21, 33, 4, 89, 71, 7]
sorted = []
for n in range(1,len(unsorted)):
    lowest = 0
    for i in range(0,len(unsorted)-1):
        if unsorted[i] < unsorted[lowest]:
            lowest = i
    sorted.append(unsorted[lowest])
    del unsorted[lowest]
print sorted
Run Code Online (Sandbox Code Playgroud)

Jef*_*ado 5

将代码从命令式语言移植到函数式语言时,您应该尝试转换代码中使用的算法,而不是代码本身恕我直言.

代码正在进行选择排序,所以你想问自己,选择排序有什么作用?

  • 找到最低限度
  • 把它放在排序列表的前面.
  • 对其余项目进行排序,将结果置于最小值之后.

那么代码会是什么样子?这当然会奏效:

let rec selection_sort = function
    | [] -> []
    | l -> let min = List.min l in                         (* find the minimum *)
           let rest = List.filter (fun i -> i <> min) l in (* find the rest *)
           let sorted_rest = selection_sort rest in        (* sort the rest *)
           min :: sorted_rest                              (* put everything together *)
Run Code Online (Sandbox Code Playgroud)