I am going to implement getting all leaves from tree to list and vice versa - for list of leaves construct tree - I know that such trees is infitity.
leaves(nil) -->
[].
leaves(t(X, nil, nil)) -->
[X].
leaves(t(_, t(Y, L, R), nil)) -->
leaves(t(Y, L, R)).
leaves(t(_, t(X, LL, LR), t(Y, RL, RR))) -->
leaves(t(X, LL, LR)),
leaves(t(Y, RL, RR)).
Is seems to be even workin, for example
phrase( leaves( t(6, t(3,
t(1, nil, nil),
t(5, nil, nil)
),
t(4,
t(2, nil, nil),
t(8,
t(7, nil, nil),
t(9, nil, nil)
)
)
)
), X).
X = [1, 5, 2, 7, 9] ;
false.
One result, as expected. However, problem is in vice versa - it is looping - of course it is obvious that there are infitely such tree - but I dosen't give any result.
phrase(leaves(X), [1, 5, 2, 7, 9])
is looping, but for
phrase(leaves(X), [1])
it seems to be working in expected way:
X = t(1, nil, nil) ;
X = t(_G8388509, t(1, nil, nil), nil) ;
X = t(_G8388509, t(_G8388513, t(1, nil, nil), nil), nil)
Is it possible to implement it such that it will be working in the same way for one-element list ?
Edit
After reexamining your prior answers, I come to following conclusions:
leaves(nil, Ls, Ls) --> [].
leaves(t(X, nil, nil), Ls, Ls) -->[X].
leaves(t(_, t(Y, L, R), nil), [_|Ls0], Ls) -->
leaves(t(Y, L, R), Ls0, Ls).
leaves(t(_, nil, t(Y, L, R)), [_|Ls0], Ls) -->
leaves(t(Y, L, R), Ls0, Ls).
leaves(t(_, t(X, LL, LR), t(Y, RL, RR)), [_|Ls0], Ls) -->
leaves(t(X, LL, LR), Ls0, Ls1),
leaves(t(Y, RL, RR), Ls1, Ls).
phrase(leaves(X, [1,2], _), [1,2]).
X = t(_G1522, t(_G1526, t(1, nil, nil), t(2, nil, nil)), nil) ;
X = t(_G1522, nil, t(_G1526, t(1, nil, nil), t(2, nil, nil))) ;
X = t(_G1522, t(1, nil, nil), t(2, nil, nil)) ;
X = t(_G1522, t(1, nil, nil), t(_G1530, t(2, nil, nil), nil)) ;
X = t(_G1522, t(1, nil, nil), t(_G1530, nil, t(2, nil, nil))) ;
X = t(_G1522, t(_G1526, t(1, nil, nil), nil), t(2, nil, nil)) ;
X = t(_G1522, t(_G1526, nil, t(1, nil, nil)), t(2, nil, nil)) ;
false.
I expected infite result, but I got finite result. However, is it incorrect ?