Zip function in Prolog

I am new to Prolog, and my job requires us to implement the function described below:

Write the Prolog predicate zip(L1,L2,L3), which is true if the list is L3obtained by zping (i.e. shuffling or interleaving) the elements of lists L1and L2. Update: lists L1and L2may have different lengths. For example, when you are done, you should get the following behavior:

?- zip([1,2],[a,b],[1,a,2,b]).
true.
?- zip([1,2],[a,b],X).
X = [1, 2, a, b] ;
X = [1, 2, a, b] ;
X = [1, a, 2, b] ;
X = [1, a, b, 2] ;
X = [a, 1, 2, b] ;
X = [a, 1, b, 2] ;
X = [a, b, 1, 2] ;
X = [a, b, 1, 2] ;
false.
?- zip([1,2],[a,b],[1,2,a,b]).
true.
?- zip(X,[a,b],[1,a,2,b]).
X = [1,2]
true.
?- zip([1,2],X,[1,a,2,b]).
X = [a,b]
true.

I am going to create a list containing items from L1and L2, and then compare the list with L3. But I am not familiar with the syntax and loops in Prolog.

+5
source share
2 answers

, . , , . .

1

, , . OCaml Python , zip - . - :

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

?- zip([1,2],[3,4],XYs).
XYs = [1-3,2-4].

Prolog. OCaml, Python, Haskell (X, Y) , Prolog (X-Y). . .

Prolog maplist. maplist , .

2

(Edit) . interlace/3 shuffle/3 . @salva . +1 ! , :

?- shuffle([1,2],[3,4],Zs).
Zs = [1,3,2,4].

. [1,2] [3,4] Prolog? , . , , Prolog. , .

?- shuffle([1,2],Ys,Zs).
Ys = [],
Zs = [1,2] ;
Ys = [_G607],
Zs = [1,_G607,2] ;
Ys = [_G607,_G616|_G617],
Zs = [1,_G607,2,_G616|_G617].

: Ys Zs , shuffle/3 ? Ys 3 :

  • [] . Zs [1,2]. , .

  • [_G607] . Zs - [1,_G607,2]. _G607 - . , , Ys, Zs. : " , , . , , .

  • [_G607,_G616|_G617] , .

:

?- shuffle(Xs,Xs,Zs).
Xs = Zs, Zs = [] ;
Xs = [_G592],
Zs = [_G592,_G592] ;
Xs = [_G592,_G601],
Zs = [_G592,_G592,_G601,_G601] ;
Xs = [_G592,_G601,_G610],
Zs = [_G592,_G592,_G601,_G601,_G610,_G610]
...

, Zs!

3

, , :

intertwine([], [], []).
intertwine([E|Es], Fs, [E|Gs]) :-
   intertwine(Es, Fs, Gs).
intertwine(Es, [F|Fs], [F|Gs]) :-
   intertwine(Es, Fs, Gs).

, , !

?- length(Zs,3), intertwine(Xs,Ys,Zs).
Zs = Xs, Xs = [_G648,_G651,_G654],
Ys = [] ;
Zs = [_G648,_G651,_G654],
Xs = [_G648,_G651],
Ys = [_G654] ;
Zs = [_G648,_G651,_G654],
Xs = [_G648,_G654],
Ys = [_G651] ;
Zs = [_G648,_G651,_G654],
Xs = [_G648],
Ys = [_G651,_G654] ;
Zs = [_G648,_G651,_G654],
Xs = [_G651,_G654],
Ys = [_G648] ;
Zs = [_G648,_G651,_G654],
Xs = [_G651],
Ys = [_G648,_G654] ;
Zs = [_G648,_G651,_G654],
Xs = [_G654],
Ys = [_G648,_G651] ;
Zs = [_G648,_G651,_G654],
Xs = [],
Ys = [_G648,_G651,_G654].
+6

L1 L2 L3 L3 L1 L2. "" , . Prolog , . . , , :

zip([], L, L) :- !.

I.e., L1 - , L3 L2.

(!/0) . Prolog, , , . , .

. .

, , . : L3 ( "" ) L1, L2 (.. , , " " ). , , .

, zip ( "" ) L1 ( L2) L3.

.

: , , , :

?- zip([1,2],X,[1,a,2,b]).

"", , ( ). , , L3 ( ground/1) .

+3

All Articles