列表中的连续元素 [英] Consecutive elements in a list

查看:53
本文介绍了列表中的连续元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阻止了 Prolog 中代码的谓词.我需要对这两个谓词进行编码:

I'm blocking on a predicate to code in Prolog. I need to code that two predicates:

如果我调用:u([a,b,c,d,e,f], X). 它将给出 X=[a,b], X=[b,c], X=[c,d] ...

If I call : u([a,b,c,d,e,f], X). it will give X=[a,b], X=[b,c], X=[c,d] ...

如果我调用:v([a,b,c,d,e,f], X). 它将给出 X=[a,b], X=[c,d], X=[e,f] ...

If I call : v([a,b,c,d,e,f], X). it will give X=[a,b], X=[c,d], X=[e,f] ...

非常感谢!

推荐答案

虽然 false 的回答更优雅,对于谓词 u/2,这里有一个更适合初学者的解决方案.

Although false's answer is more elegant, here is a solution more appropriate for beginners for your predicate u/2.

u([X,Y|_], [X,Y]).
u([_|Tail], XY):- u(Tail,XY).

第一条规则表示 [X,Y] 表示列表中的两个连续元素,如果它们是列表中的前两个元素.

The first rule says that [X,Y] represent two consecutive elements in a list if they are the first two elements in that list.

第二条规则规定,如果两个元素在列表尾部的某处连续,则它们在列表中是连续的.

The second rule states that two elements are consecutive in a list if they are consecutive somewhere in the tail of the list.

现在尝试为 v/2 找到类似的解决方案.

Now try to find a similar solution for v/2.

这篇关于列表中的连续元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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