尝试学习 F#...对整数列表进行排序
过去几个月我一直在使用 Python,现在正在尝试尝试 F#。只是……我实在是不太明白。我过去几天一直在阅读文档,但仍然不完全理解如何完成基本任务。
我一直在关注 tryfsharp.org 和 fsharp.net 上的教程。
例如,我如何完成这个用 Python 编写的基本任务,而不是用 F# 编写?
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
I've been using Python the past couple of months and now am trying to give F# a whirl. Only...I don't really get it. I've been reading documentation for the past few days and still don't completely understand how to accomplish basic tasks.
I've been following the tutorials on tryfsharp.org and fsharp.net.
For instance, how would I accomplish this basic task written in Python, in F# instead?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我意识到,如果您想要直接翻译,这可能不是您想要的,但 F# 和函数式编程往往比命令式语言更强调声明式编程。例如,如果您想对数字列表进行排序,只需对它们进行排序:
如果您在摸索 F# 时遇到困难,那么阅读一下函数式编程可能会有所帮助,以帮助您理解为什么 F# 的做法有所不同。我去年写的这篇文章可能会有所帮助 http://msdn.microsoft.com/en -us/magazine/ee336127.aspx
I realize that this might not be exactly what your looking for if you want a direct translation, but F# and functional programming tend to emphasize declarative programming more than imperative languages. For example, if you want to sort a list of numbers, just sort them:
If you're having trouble groking F#, it may be beneficial to read up on functional programming a bit to help you understand why F# does things differently. This article I wrote last year may help http://msdn.microsoft.com/en-us/magazine/ee336127.aspx
将代码从命令式语言移植到函数式语言时,您应该尝试转换代码中使用的算法,而不是代码本身(恕我直言)。
该代码正在执行选择排序,因此您想问自己,选择排序是做什么的?
那么代码会是什么样子呢?这肯定会起作用:
When porting code from an imperative language to a functional language, you should try to convert the algorithm that is used in the code, rather than the code itself IMHO.
The code is doing a selection sort so you want to ask yourself, what does the selection sort do?
So what would the code look like? This would certainly work:
请注意,您的 python 版本不正确。它输出:
缺少
7
。下面是 F# 的直接翻译:
翻译后的版本几乎与 Python 版本完全相同。但这并不是编写 F# 程序的理想方式。对于 F# 中的排序算法,您可以阅读我博客上的一篇博文:
http://fdatamining .blogspot.com/2010/03/test.html
Notice that your python version is incorrect. It outputs:
Lacks
7
.Here is a direct F# translation:
The translated version is nearly exactly the same as the Python one. But this is not the ideal way to write F# programs. For sorting algorithms in F#, you can read a blog post on my blog:
http://fdatamining.blogspot.com/2010/03/test.html