问题描述
我阻止了 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
.
这篇关于列表中的连续元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!