Interleaving Elements of a Prolog list

泄露秘密 提交于 2020-01-02 22:08:31

问题


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.

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

For example,

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!


回答1:


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).

And for your examples:

?- 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.


来源:https://stackoverflow.com/questions/39677973/interleaving-elements-of-a-prolog-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!