F# 递归终止
我阅读了大量有关函数式编程和 f# 的内容。我有一段我无法理解的代码。我熟悉递归程序,但这个特定
open System
let rec fact x =
if x < 1 then 1
else x * fact (x - 1)
fact 6
的代码让我烦恼。在这段代码中,代码中没有任何地方可以终止递归。这个程序如何知道何时停止。如果我用 c# 编写这个程序,当索引或迭代器高于 6 时,我会告诉程序停止递归。
I have been reading alot about functional programming and f#. I have a snippet of code that I cannot understand. I am familiar with recursive programs but this particular code is bugging me
open System
let rec fact x =
if x < 1 then 1
else x * fact (x - 1)
fact 6
In this snippet of code there is no where in the code that terminates the recusion. How does this program know when to stop. If I programmed this in c# I would tell the program to stop recursing when the index or iterator is higher then 6.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当
x
小于1
时,递归停止,因为表达式的结果是1
在 C# 中,函数如下所示:
Pure函数式编程很有趣,因为永远没有返回,程序所做的只是评估。您需要问自己“这个表达式的计算结果是什么?”
The recursion stops when it
x
is less than1
because the result of the expression is then1
In C# the function would look as follows:
Pure functional programming is interesting because there is never a return, all the program does is evaluate. You need to ask yourself 'What does this expression evaluate to?'