Reputation: 21
Just a small question about Prolog. Say I have used the built in predicate findall/3
to obtain a list and used the variable X
as my output.
I'm wondering how I could then use this list in another predicate such as last/2
to find the last element of this list. If you could include a small example too that would help greatly.
Upvotes: 0
Views: 789
Reputation: 476503
First of all, since Prolog aims to be a logic programming programming language, there is nu such thing as output variables.
Nevertheless, say you know a variable X
is bounded after a certain predicate and you intend to use this value when calling a new predicate, you can use Prolog's logical "and" ,/2
. I'm putting "and" between quotes because this and differs sometimes from the natural understanding of how "and" in natural language behaves.
You can thus use a predicate:
findall(A,foo(A),X),last(X,L).
To first find all occurences of foo/1
, extract the variable A
, put these into a list X
and finally get the last/2
element of X
.
You can then for instance use this in a defined predicate:
last_foo(L) :-
findall(A,foo(A),X),
last(X,L).
If you run this for instance with:
foo(a).
foo(9).
foo(b).
The results are:
?- foo(A).
A = a ;
A = 9 ;
A = b.
and:
?- findall(A,foo(A),X).
X = [a, 9, b].
Now the result to obtain the last is:
?- findall(A,foo(A),X),last(X,L).
X = [a, 9, b],
L = b.
or:
?- last_foo(L).
L = b.
Upvotes: 0