recursion - compare the elements of one list with the elements of another list in prolog -
first of all, beginner @ prolog.
i trying compare each element of list each element of list. compare, mean sending these 2 elements predicate(conflicts) wrote. far, got this:
%iterate on first list cmp_list([],_,_). cmp_list([x|y],[a|b],result):- cmp_list_inner(x,[a|b],result), cmp_list(y,[a|b],result). %iterate on second list cmp_list_inner(_,[],_). cmp_list_inner(x,[a|b],s):- not(conflicts(x,a)), %compare cmp_list_inner(x,b,[x-a|s]).%if okay, add combination, i.e x-a main list returned
the predicate cmp_list stands recursion of outer list, whereas 1 inner stands inner list. cmp_list(firstlist, secondlist, new list after combination returned.)
this doesn't work! though adds values single element in first value main list, doesn't append second comparison(for second element in first list) main list returned. result should in form of: [x1-y1], [x1-y2], [x2-y1], [x2-y2].... xs first list , ys second list.
any appreciated. thanks!
you need 1 simple predicate:
cmp_list([], [], []). % cmp_list succeeds 2 empty lists cmp_list([h1|t1], [h2|t2], [h1-h2|r]) :- % cmp_list of [h1|t1] , [h2|t2] succeeds if... \+ conflicts(h1, h2), % conflicts fails h1 , h2 cmp_list(t1, t2, r). % cmp_list succeeds t1 , t2, result r % otherwise, cmp_list fails (e.g., lists diff length)
a little more compact use built-in predicate, maplist
:
cmp_list(l1, l2, r) :- % cmp_list succeeds on l1, l2 if... maplist(no_conflicts, l1, l2, r). % no_conflicts succeeds every % corresponding pair of l1, l2 elements no_conflicts(x, y, x-y) :- \+ conflicts(x-y).
if want capture corresponding pairs don't conflict , ignore rest, then:
cmp_list([], _, []). cmp_list([_|_], [], []). cmp_list([h1|t1], [h2|t2], r) :- ( conflicts(h1, h2) -> cmp_list(t1, t2, r) ; r = [h1-h2|r1], cmp_list(t1, t2, r1) ).
this uses "if-then-else" pattern in prolog formed grouping ->
;
. create result looks like, [x1-y1, x3-y3, ...]
. can choose want form result elements changing line:
r = [h1-h2|r1]
for example, r = [[h1,h2]|r1]
yield result looks like, [[x1,y1], [x3,y3], ...]
.
more general problem (i.e., 1 looking :)), i'll start original code modify it's needed:
%iterate on first list cmp_list([], _, []). cmp_list([x|t], l2, result):- cmp_list_inner(x, l2, r1), cmp_list(t, l2, r2), append(r1, r2, result). %iterate on second list cmp_list_inner(_, [], []). cmp_list_inner(x, [a|b], r) :- ( conflicts(x, a) -> cmp_list_inner(x, b, r) ; r = [x-a|t], cmp_list_inner(x, b, t) ).
Comments
Post a Comment