在 Prolog 中删除 List L 的最后 3 个元素以生成 List L1
我如何编写一个目标,从列表 L 中删除最后三个元素,生成另一个列表 L1?
另外,我将如何编写多个目标来从生成 L2 的列表 L 中删除前三个元素和最后三个元素?
How do i write a goal that deletes the last three elements from a list L producing another list L1?
Also, how would I write multiple goals to delete the first three elements and the last three elements from a list L producing L2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Prolog 与其他语言有点不同,但它也有一个值得学习的库(标准 ISO):
现在另一个请求就很容易了:
测试:
Prolog it's a bit different from other languages, but it also has a libray (standard ISO) that's worth to learn:
Now the other request come easy:
Test:
您可能想尝试这样的操作:
第一个谓词将返回一个没有最后三个元素的列表,如果元素少于三个,则失败。
第二个谓词将返回一个没有前三个元素和最后三个元素的列表,如果元素少于六个则失败。
You might want to try something like this:
The first predicate will return a list without the last three elements, and fail in case there are less than three elements.
The second predicate will return a list without the first and last three elements, and fail in case there are less than six elements.
逻辑编程的第一步,从基本情况开始。当元素少于三个时你希望发生什么?我猜你想要一个空列表?
现在,对于包含三个以上元素的列表,您希望保留第一个元素,并从其余元素中删除三个元素。您可能首先尝试编写:
但这会由于回溯而导致错误的结果。解决这个问题的最简单方法是验证 L 是否具有三个以上元素:
但更优雅的解决方案是使用 Prolog 的 cut 运算符:
要实现 without_first_third,又不会感到无聊,您可以简单地反转列表,删除最后三个,然后再翻回来:
或者你可以写下一些非常简单的规则:(
想一想,也许用 without_first_third 来实现 without_last_third 会更好,而不是相反)!
Step one of logic programming, start with the base cases. What do you want to happen when there are fewer than three elements? I guess you want an empty list?
Now, for a list with more than three elements, you want to keep the first element, and remove three from the remaining elements. You might first try to write:
but this will cause incorrect results due to back-tracking. The simplest way to fix that is to verify that L has more than three elements:
But a more elegant solution would be to use Prolog's cut operator:
To implement without_first_three, without getting bored, you could simply reverse the list, remove the last three, and flip it back again:
or you could just write down some really simple rules:
(Thinking about it, maybe it would be nicer to implement without_last_three in terms of without_first_three, not the other way around)!