algorithm - 功能替代品?

标签 algorithm language-agnostic functional-programming loops

随着我继续学习函数式编程,我来了 想知道是否可以替代我默认的“程序”方式 的思考。更具体地说,我在看一个函数 写了。这是它的作用:

Swap two elements of an unordered list of numbers, such that one of the elements  
 is now in the right place
Add the sum of the swapped values to an accumulated total   
Repeat until list is sorted

所以,现在我正在使用一个带有 accum 变量的标准循环*来做 以上。它工作正常,而且肯定没有错 与现实生活中的迭代,但作为这个练习的重点是 扩展我的思维方式,我很好奇是否有更实用的 上述算法的方法。

谢谢!

*(实际上是递归,但无论如何)

最佳答案

From EigenClass:

The venerable master Leroy was walking with his student. Wishing to start a discussion with his master, the apprentice said "Master, I've heard that all loops must be replaced with tail-recursive functions. Is that true?" Leroy looked commiseratively at his student and replied "Foolish pupil, many tail-recursive functions are merely inefficient loops."

The student spent the next few weeks replacing tail-recursive functions with explicit loops. He finally showed his code to master Leroy, seeking his approval. Leroy hit him with a stick. "When will you learn? Explicit loops are a poor man's tail-recursive functions." At that moment, the student became enlightened.

编辑:引用 OCaml 的主要开发人员 Xavier Leroy

因为我无法看到您的函数来理解它的功能*,所以我不知道。但看起来你所做的是正确的。我的主要建议是查看适合函数式编程的数据结构——但是您使用的是列表,所以这是不可能的,尽管在这种情况下列表不是最好的数据结构。以及算法。如果您沉迷于使用插入排序,那么您可能无法使用归并排序或其他更高效的方法。

关于algorithm - 功能替代品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/318128/

相关文章:

validation - 用于指定值约束的通用语言

functional-programming - 方案中的可变数据返回对,其中右侧元素是匹配条件的最大后缀

functional-programming - 学习CnC车床编程

c - 以特定顺序获取字符串组合的递归算法

c - 使用凯撒密码加密文本

algorithm - 为了理解算法分析书籍而需要学习的数学领域列表(例如算法简介)

javascript - 删除数组中对象中的重复键并聚合每个状态 Javascript 的总数

image-processing - 在 2D 网格上插值

language-agnostic - 一种语言可以图灵完整但在其他方面不完整吗?

相当于 LINQ SelectMany() 的 Java Stream