问题
Write a predicate
cmp_list/3
, the first 2 arguments are 2 lists, and the last one isComparison
which meansge
,lt
,le
, orgt
.ge
: greater or equallt
: less thanle
: less or equalgt
: greater than
the output should be like this:
the first two lists represent a version of a software, and the function is used to compare two versions of a software to see which one is newer:
?- cmp_list([2,3,4], [2,3,5], C).
C = lt ;
C = le .
?- cmp_list([1,2,3,4], [1,1,8], C).
C = gt ;
C = ge .
回答1:
This smells like homework, so I'll just give you a couple of hints.
- If both lists are empty, they're equal (
le
orge
). - If first list is empty, you have something like
[], [V|Vt], ...
which could be the end of the recursion when comparing, say 1.2 and 1.2.3, so the third argument should belt
. - Similarly, if the second list is empty, the third argument should be
gt
. - If both are non-empty, you should compare the heads. If they differ, answer
gt
orlt
accordingly. If they are equal, recurse on the tails.
来源:https://stackoverflow.com/questions/11620781/how-to-write-a-cmp-list-3-function-in-prolog