Prolog Zip 函数

ama*_*man 2 prolog

我在序言中的 nrew。我正在尝试学习 zip 功能。问题是这样的。

zip(L1, L2, X):列表 X 是通过“压缩”前 2 个参数形成的。

结果应该是这样的:

?- zip([a, b, c], [x, y, z], X).
L = [a, x, b, y, c, z]
?- zip([a, b], [x, y, z], X).
false
?- zip([a, b, c, d], X, [a, p, b, q, c, r, d, s]).
X = [p, q, r, s]
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经这样做了。我可以得到 1st 3rd 的结果,但不能得到 2nd 的结果。任何人都可以帮我解决第二个问题。谢谢你

zip([X],[Y],[X,Y]).  
zip([], [], []).
zip([X|Xs], [Y|Ys], [X,Y|Zs]) :-
   zip(Xs,Ys,Zs).

zip([X|Xs],[],[X|Xs]).
zip([Y|Ys],[],[Y|Ys]).

zip(Xs, [], Xs).
zip([], Ys, Ys).
Run Code Online (Sandbox Code Playgroud)

我如何定义这个功能在哪里;allsame(L):列表 L 包含相同的元素。我应该得到这个。

?- allsame([b, b, b]).
true
?- allsame([c, c, c, Y, c, c, X, c]).
X = c, Y = c
Run Code Online (Sandbox Code Playgroud)

m09*_*m09 5

你有它:

zip([], [], []).
zip([X|Xs], [Y|Ys], [X,Y|Zs]) :- zip(Xs,Ys,Zs).
Run Code Online (Sandbox Code Playgroud)

仅此一项就足以定义您正在寻找的关系。额外的条款没有帮助。

测试:

?- zip([a, b, c], [x, y, z], X).
X = [a, x, b, y, c, z].

?- zip([a, b], [x, y, z], X).
false.

?- zip([a, b, c, d], X, [a, p, b, q, c, r, d, s]).
X = [p, q, r, s].
Run Code Online (Sandbox Code Playgroud)