0

how can I accomplish this:

Give a tail-recursive definition for each of the following predicates.
power(X,Y,Z): XY=Z.
gcd(X,Y,Z): The greatest common divisor of X and Y is Z.
sum(L,Sum): Sum is the sum of the elements in L.

so far I have done this but not sure if that's correct

power(_,0,1) :- !.
power(X,Y,Z) :- Y1 is Y - 1,power(X,Y1,Z1),Z is X * Z1.

sum(void,0).
sum(t(V,L,R),S) :- sum(L,S1),sum(R,S2),  S is V + S1 + S2.
false
  • 10,264
  • 13
  • 101
  • 209
FRANK
  • 1
  • 1
  • 2
  • 1
    If you're not sure it's correct, TEST IT. – Matt Ball Oct 12 '09 at 14:57
  • Frank: if you indent text 4 spaces, it will format it as code. Edit your question and give it a try. The orange question mark in the editor toolbar links to a document with other formatting markup. – outis Nov 15 '09 at 06:59

1 Answers1

2

These are not tail recursive. You can write tail recursive variants by using an accumulator, see this answer.

Your sum is over a tree, which is unusual, normally one would use a list. In Prolog [] is the empty list and [X|R] is the pattern for a nonempty list with the head X and the tail R.

Community
  • 1
  • 1
starblue
  • 55,348
  • 14
  • 97
  • 151
  • Sir, please can u help me write the power in recursive fashion? I just started learning it and can't do it.Please help me with one of them at least. Thanks Frank – FRANK Oct 12 '09 at 15:28
  • 2
    It's your homework, not mine. I'm not even your instructor. Sorry, I won't give you specific solutions, you are supposed to learn thinking for yourself. – starblue Oct 12 '09 at 16:09