如何在 Prolog 中编写 cmp_list/3 函数? [英] How to write a cmp_list/3 function in Prolog?
本文介绍了如何在 Prolog 中编写 cmp_list/3 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
写一个谓词cmp_list/3
,前2个参数是2个list,最后一个是Comparison
,意思是ge
,lt
、le
或 gt
.ge
:大于或等于lt
:小于le
:小于或等于gt
:大于
输出应该是这样的:
前两个列表代表一个软件的版本,该函数用于比较一个软件的两个版本,看看哪个版本更新:
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 equal
lt
: less than
le
: less or equal
gt
: 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 .
推荐答案
这闻起来像作业,所以我只是给你一些提示.
This smells like homework, so I'll just give you a couple of hints.
- 如果两个列表都为空,则它们相等(
le
或ge
). - 如果第一个列表为空,则您有类似
[], [V|Vt], ...
之类的内容,在比较 1.2 和 1.2.3 时,这可能是递归的结束,所以第三个参数应该是lt
. - 同样,如果第二个列表为空,则第三个参数应为
gt
. - 如果两者都不为空,则应比较正面.如果它们不同,请相应地回答
gt
或lt
.如果它们相等,则在尾部递归.
- 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.
这篇关于如何在 Prolog 中编写 cmp_list/3 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文