如何在Prolog中编写cmp_list / 3函数? [英] How to write a cmp_list/3 function in Prolog?

查看:218
本文介绍了如何在Prolog中编写cmp_list / 3函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


写一个谓词 cmp_list / 3 ,前两个参数是2个列表,最后一个是比较表示 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 is Comparison which means ge, lt, le, or gt.
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 or ge).
  • 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 be lt.
  • 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 or lt accordingly. If they are equal, recurse on the tails.

这篇关于如何在Prolog中编写cmp_list / 3函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆