Home > Archive > Prolog > April 2005 > Why does this recursion not work?
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Why does this recursion not work?
|
|
| Anders Lindén 2005-04-17, 8:56 pm |
| %to get the tail of the sequence
tail(sekv(D,T),T).
%find the last element:
last(nil,nil).
last(sekv(D,nil),D). %only one element left
%the recursion
last(sekv(D,R),R2):- last(tail(R,R2),R2).
Why does this recursion not work?
| |
| Bill Spight 2005-04-17, 8:56 pm |
| Dear Anders,
> %to get the tail of the sequence
>
> tail(sekv(D,T),T).
>
> %find the last element:
>
> last(nil,nil).
>
> last(sekv(D,nil),D). %only one element left
>
> %the recursion
>
> last(sekv(D,R),R2):- last(tail(R,R2),R2).
>
> Why does this recursion not work?
>
>
Look at the last clause of last/2. Translate it into your native tongue.
Does it say what you intend it to say?
Also note that 'tail(R,R2)' does not unify with 'nil' or 'sekv(A,B)'. So
it is going to fail. If you want to say last(Tail,Last), where Tail is
the tail of Sekv, I think you want this:
tail(Sekv,Tail),
last(Tail,Last).
In English, the tail of Sekv is Tail, and the last element of Tail is
Last.
Note also that the use of descriptive variable names helps readability.
Best wishes,
Bill
| |
| George Sp 2005-04-18, 8:57 pm |
| Hi,
May be it does not work because there is no clause for
last(tail(Something, SomethingElse), SomethingElse)
"Anders Lindén" <xxxx@xxx.xx> wrote in message
news:42624b12$1@griseus.its.uu.se...
> %to get the tail of the sequence
>
> tail(sekv(D,T),T).
>
> %find the last element:
>
> last(nil,nil).
>
> last(sekv(D,nil),D). %only one element left
>
> %the recursion
>
> last(sekv(D,R),R2):- last(tail(R,R2),R2).
>
> Why does this recursion not work?
>
>
>
>
| |
| student 2005-04-19, 3:59 am |
| Anders Lindén wrote:
> %to get the tail of the sequence
>
> tail(sekv(D,T),T).
>
> %find the last element:
>
> last(nil,nil).
>
> last(sekv(D,nil),D). %only one element left
>
> %the recursion
>
> last(sekv(D,R),R2):- last(tail(R,R2),R2).
>
> Why does this recursion not work?
>
To save ink, I will replace your 'sekv' functor with the single-letter
functor 'd'.
What is the "tail" and what is the "last elment" in each of these cases:
nil
d(X,Y)
d(a,d(X,Y))
d(a,d(X,d(Y,nil)))
|
|
|
|
|