过去几个月我一直在使用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
答案 0 :(得分:5)
当将代码从命令式语言移植到函数式语言时,您应该尝试转换代码中使用的算法,而不是代码本身恕我直言。
代码正在执行selection sort,所以你想问问自己,选择排序有什么作用?
那么代码会是什么样子?这当然会奏效:
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 *)
答案 1 :(得分:4)
请注意您的python版本不正确。它输出:
[4, 8, 9, 15, 21, 33, 71, 82, 89]
缺乏7
。
这是一个直接的F#翻译:
let unsorted = new ResizeArray<int> ([| 82; 9; 15; 8; 21; 33; 4; 89; 71; 7 |])
let sorted = new ResizeArray<int> ()
for n=1 to unsorted.Count-1 do
let mutable lowest = 0
for i=0 to unsorted.Count-1 do // i changed this line so the output is correct.
if unsorted.[i] < unsorted.[lowest] then
lowest <- i
sorted.Add(unsorted.[lowest])
unsorted.RemoveAt(lowest)
printfn "%A" (sorted |> Seq.toArray)
翻译版本几乎与Python版本完全相同。但这不是编写F#程序的理想方式。对于F#中的排序算法,您可以在我的博客上阅读博客文章:
答案 2 :(得分:2)
我意识到如果你想要直接翻译,这可能不是你想要的,但是F#和函数式编程倾向于强调声明性编程而不是命令式语言。例如,如果要对数字列表进行排序,只需对它们进行排序:
let unsorted = [2; 9; 15; 8; 21; 33; 4; 89; 71; 7]
let sorted = unsorted |> List.sort
//now print em out
sorted |> List.iter (printfn "%d")
如果您在浏览F#时遇到问题,那么阅读函数式编程可能会有所帮助,以帮助您理解为什么F#以不同的方式执行操作。我去年写的这篇文章可以帮助http://msdn.microsoft.com/en-us/magazine/ee336127.aspx