简体   繁体   中英

How to write a complst/3 predicate with Prolog?

Write a predicate complst/3 that is true if the given versions have the given order relationship. The order will be: one of lt, le, gt, ge, or eq (less-than, less-or-equal, greater-than, greater-or-equal, equal-to) and the predicate should be true for all of the relationships that apply. For example,

?- complst([2,3,4], [2,3,5], C).
C = lt ;
C = le .

?- complst([1,2,3,4], [1,1,8], C).
C = gt ;
C = ge .

In order to get the goal, I wrote a predicate:

complst([], [], Cmp) :-
    Cmp = eq, !.

complst([A], [B], Cmp) :-
    A > B,
    Cmp = gt.

complst([A], [B], Cmp):-
    A < B,
    Cmp = lt.

complst([A], [B], Cmp):-
    A >= B,
    Cmp = ge.

complst([A], [B], Cmp):-
    A =< B,
    Cmp = le.

complst([], [B], Cmp):-
    Cmp = le, !.

complst([], [B], Cmp):-
    Cmp = lt, !.

complst([A], [], Cmp):-
    Cmp = ge, !.

complst([A], [], Cmp):-
    Cmp = gt, !.

complst([X|XS], [Y|YS], Cmp):-
    X > Y,
    cmp_list([X], [Y], Cmp).

complst([X|XS], [Y|YS], Cmp):-
    X < Y,
    cmp_list([X], [Y], Cmp).

complst([X|XS], [Y|YS], Cmp):-
    X == Y,
    cmp_list(XS, YS, Cmp).

But the problem is, the output will never stop unless I press enter. Anyone can help me to fix this problem please?? Thanks in advance!!

There are only three possibilities in comparing two software version lists in this way. Either the first is less than, equal, or greater than the second. In the first case lt,le fit. In the second case le,eq,ge fit. In the third - ge,gt .

That means that you can compare elements of the two lists pairwise. As soon as the first or the third case is detected, you can immediately produce the values. Otherwise, continue on to the next pair or elements.

The standard skeleton of recursion along two lists is

recur( [], [], X):- end_of_two_lists_reached(X).
recur( [], [_|_], X):- second_list_is_longer(X).
recur( [_|_], [], X):- first_list_is_longer(X).
recur( [A|A2], [B|B2], X):- two_elements_are(A,B,C),
  (   continue_recursing(C)
  ->  recur(A2,B2,X) 
  ;   stop_recursing(C,X) 
  ).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM