2011-05-24 61 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