Search code examples
listprolog

Prolog evaluating how two lists compare to eachother


Note: Near complete beginner to logic programming

I need to compare two lists of integers and figure out if one is greater, greater-equal, or they are both equal.

For example:

compare_list([1, 2, 3], [1, 2, 4], C).
C = greater,
C = greater-equal.
compare_list([1, 2, 3], [1, 2, 4], C).
C = equal.

So far the closest I have been able to get has been...

compare_list([],[],_).
compare_list([X|XS],[Y|YS],C):-
  X > Y,
  compare_list(XS,YS,C),
  C = 'greater'.

compare_list([X|XS],[Y|YS],C):-
  X >= Y,
  compare_list(XS,YS,C),
  C = 'greater-equal'.

compare_list([X|XS],[Y|YS],C):-
  X == Y,
  compare_list(XS,YS,C),
  C = 'equal'.

Now that obviously doesn't work as needed because it is always comparing the first element of each list and seeing if the C value holds for all of the values. However I cannot think of a way to make it work as intended.

Edit: The earlier a value is in a list, the more important it is. So [2,2] > [1,3] > [1,2]

Tips would be appreciated. Thanks.

Edit: Solved by waiting until the end to assign C to anything.


Solution

  • According to your definition of "greater" there is no need to continue the recursion after you find that X>Y. If you reach the end of the recursion (as chac said) you'll know that the two lists are equal.

    To get "greater-equal" you should instead check that X is not less than Y. You may think of this as "if X is less than Y than fail". Take a look at negation as failure.