I want to find a specific list inside a list of lists in prolog, let's say the list is:
L[L1,L2,L3......]
every list inside L is in the format:
L1[A,B,C,D]
I want to find a Ln with the smallest A, how can I do it?
The base case is the list with a single element (list):
find([X],X).
Then, recursively, you can compare the list of the head with the smallest list of the tail:
find([[X|Xs]|T],[X|Xs]) :- find(T,[Y|_]), X =< Y.
find([[X|_]|T],[Y|Ys]) :- find(T,[Y|Ys]), X > Y.
or more efficiently:
find([[X|Xs]|T],L) :- find(T,[Y|Ys]), (X =< Y, L = [X|Xs] ; X > Y, L = [Y|Ys]).
For example:
?- find([[3,1,4,3],[1,1,2,4],[2,4,3,1]],X).
X = [1, 1, 2, 4] ;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.