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

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

问题描述

写一个谓词cmp_list/3,前2个参数是2个list,最后一个是Comparison,意思是geltlegt.
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.

  • 如果两个列表都为空,则它们相等(lege).
  • 如果第一个列表为空,则您有类似 [], [V|Vt], ... 之类的内容,在比较 1.2 和 1.2.3 时,这可能是递归的结束,所以第三个参数应该是 lt.
  • 同样,如果第二个列表为空,则第三个参数应为 gt.
  • 如果两者都不为空,则应比较正面.如果它们不同,请相应地回答 gtlt.如果它们相等,则在尾部递归.
  • 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天全站免登陆