1

I'm new to prolog. I'm doing a recursive program the problem is that even though it prints the answer.. it doesn't stop after printing the answer and eventually gives "Out of local stack". I've read it could be a left recursion issue but as I've already told you I'm new to prolog and I don't really understand what happens... so.. here's code.

f(X, Y):-
    Y is sqrt(1-((X-1)*(X-1))).

sum(SEGMENTS, 1, TOTAL):-
    f(2/SEGMENTS*1,H1),
    TOTAL is (2/SEGMENTS)*H1.

sum(SEGMENTS, NR, TOTAL):-
    N1 is (NR-1),
    sum(SEGMENTS, N1, S1),
    f(2/SEGMENTS*NR,H1),
    f(2/SEGMENTS*N1,H2),
    TOTAL is S1 + (2/SEGMENTS)*((H1+H2)/2).

It's supposed to calculate a semicircle area with the trapezoid rule or something similar. As I've already told you .. it does finishes but after getting to the base case sum(segments, 1, total) it calls the function with the second alternative... :S

Thanks guys!

Also: Here's what I get when I run it

?- sum(3000,3000,TOTAL).
TOTAL = 1.5707983753431007 ;
ERROR: Out of local stack
2
  • Thank you very much! And yes.. when I traced it I noticed it.. I was trying to avoid the IF clause :) Commented Nov 4, 2013 at 0:21
  • mbratch, please add your response as an answer so I can mark this as answered and give you the credit for it :) Commented Nov 4, 2013 at 10:46

1 Answer 1

2

The problem is that backtracking will attempt the case of NR value of 1 on the second sum clause after the first clause has succeeded. This causes a long recursion process (since NR is being decremented continually for each recursive call, attempting to wrap around through all negative integer values, etc).

A simple way to resolve the problem is in your second sum clause. Since the intention is that it is for the case of NR > 1, put NR > 1 as your first statement:

sum(SEGMENTS, NR, TOTAL) :-
    NR > 1,
    N1 is (NR-1),
    sum(SEGMENTS, N1, S1),
    f(2/SEGMENTS*NR,H1),
    f(2/SEGMENTS*N1,H2),
    TOTAL is S1 + (2/SEGMENTS)*((H1+H2)/2).

Also note that the expression f(2/SEGMENTS*NR, H1) doesn't compute the expression 2/SEGMENTS*NR and pass it to f. It actually passes that expression symbolically. It just happens to work here because f includes it on the right hand side of an is/2 so it is evaluated as desired. If you trace it, you'll see what I mean.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.