我的代码中是否存在无限循环?在ocaml
问题描述:
我想获得函数f(i)值的总和,当i等于a到b时,f(i)+ f(a + 1)+ ... + f(b-1)+ f(b) 所以我写了这样的代码。我的代码中是否存在无限循环?在ocaml
let rec sigma : (int -> int) -> int -> int -> int
= fun f a b ->
if a=b then f a
else f b + sigma f a b-1 ;;
但结果是在评估期间存在堆栈溢出。有无限循环吗?为什么?
答
sigma f a b-1
被解析为(sigma f a b) - 1
而不是您的意图,sigma f a (b-1)
。由于sigma f a b
在您的代码中递归调用sigma f a b
,因此它永不停止。
最佳做法是在二进制运算符周围放置空格,如sigma f a b - 1
,这样就不会误读您写的内容。
顺便说一句,本周我们已经收到了4次相同的问题。我们应该警告教师或助教。它是OCaml MOOC吗? – camlspotter
优秀点。 –
谢谢你的回答,非常抱歉无法搜索问题。这不是MOOC。 – Volnyar