Volnyar
Volnyar

Reputation: 11

Is there a infinite loop in my codes? in ocaml

I want to get the sum of function f(i) values when i is equal from a to b = f(a)+f(a+1)+...+f(b-1)+f(b) So I wrote code like this.

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 ;;

but result is that there is stack overflow during evaluation. Is there a infinite loop? and why?

Upvotes: 0

Views: 582

Answers (1)

camlspotter
camlspotter

Reputation: 9040

sigma f a b-1 is parsed as (sigma f a b) - 1 instead of your intention, sigma f a (b-1). Since sigma f a b calls sigma f a b recursively in your code, it never stops.

The best practice is to put white spaces around binary operators like sigma f a b - 1 so that you would not misread what you write.

Upvotes: 3

Related Questions