Prolog, how do I make a list of lists into one list?

I want to build a list of a list for alternating each other in one list, for example: coon ([[1,4], [2,5], [3,6]], X) should return X = 1, 2,3,4 , 5.6. and there is a condition that each subscriber must have only one length, otherwise he must fail, for example [[q, r, y], [a, e], [c, g, t], X] shouid fail, and the cone ([A, B, C], [q, w, e, r, t, y]) should return only one solution, that is, A = [q, r], B = [w, t], C = [ e, y]. my recent approach.

  conns([],[]).
  conns([[Head|Tail]|X],[Head|Y]):-
    append(X,[Tail],X2),
    conns(X2,Y).                                                

conns([[]|T],A):-
    conns(T,A).

This gives me some solutions when I try to use coon ([A, B, C], [q, w, e, r, t, y]). I tried the clock to figure it out, but it all failed. How should I return a single list for each list containing the same length? Thank you very much!

+4
source share
2 answers

The problem you are facing is related to this predicate clause:

conns([[]|T],A):-
    conns(T,A).

This allows solutions to be more general than you want to define. In particular, if I understand the problem correctly, the first argument connsshould always be a list whose elements are lists of the same length. This would mean that if it [[]|T]is the first argument, and you expect it to conns([[]|T], A)succeed, then Tit will also look like [[]|R]or []. That is, it should be a (possibly empty) list of empty lists.

If you change the case with an empty list according to this restriction, your solution will work:

% The case where the first argument consists of non-empty lists    
conns([[Head|Tail]|X], [Head|Y]):-
    append(X, [Tail], X2),
    conns(X2, Y).

% Base case in which first argument is a list of empty lists
conns([], []).
conns([[]|T], []) :-
    conns(T, []).

Now, when you run the query, you get the following:

| ?- conns([[1,4],[2,5],[3,6]], R).

R = [1,2,3,4,5,6] ? ;

no
| ?-

As well as:

| ?-  conns([A,B,C], [q,w,e,r,t,y]).

A = [q,r]
B = [w,t]
C = [e,y] ? a

no
| ?-

, , .

+2
:- use_module(library(clpfd),[transpose/2]).

connsx(Xss, Xs) :-
   transpose(Xss, XssT),
   append(XssT, Xs).
+4

Source: https://habr.com/ru/post/1685957/


All Articles