2011-05-24 31 views
2

過去幾個月來我一直在使用Python,現在我試圖給F#一個旋轉。只有...我真的不明白。過去幾天我一直在閱讀文檔,但仍未完全理解如何完成基本任務。試圖學習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

「我一直在使用Python過去幾個月,現在我想給F#一掄......,但仍沒有完全瞭解如何完成基本任務。 「別擔心,在F#開始的幾周內你會覺得這樣,然後點擊它,你就無法想象*不會*使用F#。 – TechNeilogy 2011-05-24 17:45:03

回答

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 *) 
+0

奇妙的習慣。但是我真正喜歡用F#/ Ocaml的是,它可以讓你做到這一點,就像這樣,或者像Yin Zhu給出的版本。 – ThomasH 2011-05-24 08:15:59

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#排序算法,你可以閱讀我的博客博客文章:

http://fdatamining.blogspot.com/2010/03/test.html

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") 

如果您無法groking F#,它可能是有益的功能性編程讀了一下,以幫助您理解爲什麼F#以不同的方式做事。去年寫過的這篇文章可能有所幫助http://msdn.microsoft.com/en-us/magazine/ee336127.aspx