交错 Prolog 列表的元素

问题描述:

我是 Prolog 的新手,遇到了这个练习.问题要求定义一个谓词

I am new to Prolog and came across this practice excercise. The question asks to define a predicate

zipper([[List1,List2]], Zippered). //this is two lists within one list.

此谓词应将 List1 的元素与 List2 的元素交错.

This predicate should interleave elements of List1 with elements of List2.

例如

zipper([[1,3,5,7], [2,4,6,8]], Zippered) -> Zippered = [1,2,3,4,5,6,7,8].

zipper([[1,3,5], [2,4,6,7,8]], Zippered) -> Zippered = [1,2,3,4,5,6,7,8].

到目前为止,我有两个不同列表的解决方案:

So far I have a solution for two different list:

zipper ([],[],Z).
zipper([X],[],[X]). 
zipper([],[Y],[Y]).
zipper([X|List1],[Y|List2],[X,Y|List]) :- zipper(List1,List2,List).

我不确定如何将这个解决方案翻译成一个列表.任何关于我可以从哪里开始的建议都会非常有帮助!

I am not sure how I can translate this solution for one list. Any suggestion on where I can start would be greatly helpful!

首先你应该把 zipper ([],[],Z). 改为 zipper ([],[],[])..然后,为了使其适用于一个列表,您可以按照评论中推荐的垫子进行操作,或者您可以稍微更改一下.所以我的版本是:

Firstly you should change zipper ([],[],Z). to zipper ([],[],[]).. Then to make it work for one list you could do what mat recommended in the comment or you could change it a little. So my version is:

 zipper([],[],[]).
 zipper([X,[]],X). 
 zipper([[],Y],Y).
 zipper([[X|List1],[Y|List2]],[X,Y|List]) :- zipper([List1,List2],List).

对于您的示例:

?- zipper([[1,3,5,7], [2,4,6,8]], Zippered).
Zippered = [1, 2, 3, 4, 5, 6, 7, 8] ;
Zippered = [1, 2, 3, 4, 5, 6, 7, 8] ;
false.

?- zipper([[1,3,5],[2,4,6,7,8]],Zippered).
Zippered = [1, 2, 3, 4, 5, 6, 7, 8] ;
false.