Re: question about last call optimization
- From: "Neng-Fa Zhou" <nzhou@xxxxxxx>
- Date: Wed, 27 Jul 2005 00:58:32 GMT
"blindsearch" <dpatte3@xxxxxxxxxxx> wrote in message
news:1122418036.807489.196470@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
>I have a question about last call optimization using euclids algorithm
> as an example. Okay the prolog literature gives the procedure as:
>
> gcd(A,0,A).
> gcd(A,B,GCD) :- B > 0, C is A mod B, gcd(B,C,GCD).
>
> Now will prolog "last call optimize" this. It is easy to see that when
> prolog gets to the goal gcd(B,C,GCD) in the last clause that there are
> no alternative clauses. I am assuming then that this procedure is "last
> call optimized". Is this true?
It is true in most Prolog systems.
> What about if we switch the order of the clauses as such:
>
> gcd(A,B,GCD) :- B > 0, C is A mod B, gcd(B,C,GCD).
> gcd(A,0,A).
>
> Now upon reaching the last goal in the first clause, prolog can not
> determine that there are no alternative clauses. Right?
Because of the existence of a choice point, the last call cannot reuse the
frame of the caller in this predicate. But if you rewrite it into the
following:
gcd(A,B,GCD) :- B > 0, C is A mod B, gcd(B,C,GCD).
gcd(A,B,GCD):-B=:=0,GCD=A.
then you still have last-call optimization in some Prolog systems (e.g.,
B-Prolog).
> Okay finally, say we write:
>
> gcd(A,0,GCD) :- !, GCD = A.
> gcd(A,B,GCD) :- T is A mod B, gcd(B,T,GCD).
>
> Now, this should be "last call optimized" right? So in terms of speed
> of execution would this last example execute equivalently to the first?
> What about to the second?
>
> One more question. There is no big difference between the three
> versions of gcd. The first two do leave behind some choicepoints
> whereas the last does not leave any behind. So is there any point in
> writing it the last way? We're not supposed to use cuts all the time
> right? or is it a good habit to get into in the event that we run into
> procedures that have the potential of leaving behind a lot of choice
> points?
The difference should be very big. The version that is deterministic and
tail-recursive is the fastest and takes the least amount of memory.
You may want to add a version that uses if-then-else into your collectition.
--nf
.
- Follow-Ups:
- Re: question about last call optimization
- From: Bart Demoen
- Re: question about last call optimization
- References:
- question about last call optimization
- From: blindsearch
- question about last call optimization
- Prev by Date: language of postings (was Re: turbo prolog or visual prolog)
- Next by Date: Re: language of postings (was Re: turbo prolog or visual prolog)
- Previous by thread: question about last call optimization
- Next by thread: Re: question about last call optimization
- Index(es):
Relevant Pages
|