当谈到F#时,我非常环保,而且我遇到了一个处理递归函数的小问题,我希望能帮助我理解.
我有一个函数应该吐出下一个偶数:
let rec nextEven(x) =
let y = x + 1
if y % 2 = 0 then y
else nextEven y
// This never returns..
nextEven 3;;
Run Code Online (Sandbox Code Playgroud)
我使用'rec'关键字使它会递归,但是当我使用它时,它会因某种原因在无限循环中运行.如果我像这样重写函数:
let nextEven(x) =
let y = x + 1
if y % 2 = 0 then y
else nextEven y
Run Code Online (Sandbox Code Playgroud)
然后一切正常(没有rec关键字).出于某种原因,我虽然我需要'rec',因为函数是递归的(为什么我不这样做?)为什么函数的第一个版本会永远运行?
编辑
原来这是一个总的noob错误.我已经创建了该函数的多个定义,如注释+答案中所述.
我怀疑你有多个定义nextEven.这是您的第二个示例编译的唯一解释.摄制:
module A =
let rec nextEven(x) =
let y = x + 1
if y % 2 = 0 then y
else nextEven y
open A //the function below will not compile without this
let nextEven(x) =
let y = x + 1
if y % 2 = 0 then y
else nextEven y //calling A.nextEven
Run Code Online (Sandbox Code Playgroud)
尝试重置您的FSI会话.