1

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!

false
  • 10,264
  • 13
  • 101
  • 209
  • 1
    This seems very easy, since you already have all ingredients. You only need to invoke your predicate in the right way: `zipper([[List1,List2]], Zippered) :- zipper(List1, List2, Zippered).` Note that `[[List1,List2]]` is definitely **not** a good way to represent a pair of lists. Either use separate arguments, or use the customary `(-)/2` operator to denote pairs: `List1-List2`. – mat Sep 24 '16 at 15:40

1 Answers1

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.
coder
  • 12,832
  • 5
  • 39
  • 53