How to write a cmp_list/3 function in Prolog?

家住魔仙堡 提交于 2019-12-20 06:03:01

问题


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 .

回答1:


This smells like homework, so I'll just give you a couple of hints.

  • 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.


来源:https://stackoverflow.com/questions/11620781/how-to-write-a-cmp-list-3-function-in-prolog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!