Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog, how should I construct a list of list to a single list?

Tags:

prolog

I want to construct a list of list to interleave each other to a single list like: coon([[1,4],[2,5],[3,6]], X) should return X=1,2,3,4,5,6. and there is a condition that each sublist should only have the same length, otherwise, it should fail such as [[q,r,y],[a,e],[c,g,t],X] shouid fail, and coon([A,B,C],[q,w,e,r,t,y]) should only return one solution, that is A=[q,r],B=[w,t],C=[e,y]. my recent approach is.

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

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

It gives me multiple solutions when I try coon([A,B,C],[q,w,e,r,t,y]). I have been trying hours to figure it out but all failed. How should I return the single list to each sub-lists that contain the same length? Thank you so much!

like image 536
Yi Justin Avatar asked Sep 19 '17 13:09

Yi Justin


People also ask

How do you concatenate lists in Prolog?

It can be done by using append. concatenate(List1, List2, Result):- append(List1, List2, Result). Hope this helps.

How do you create a list in Prolog?

In Prolog list elements are enclosed by brackets and separated by commas. Another way to represent a list is to use the head/tail notation [H|T]. Here the head of the list, H, is separated from the tail of the list, T, by a vertical bar. The tail of a list is the original list with its first element removed.

What is a difference list in Prolog?

Definition. A Difference list in Prolog is a normal list except the very end of it is a logic variable, paired with that variable. For example: [a,b,c|E]-E.


1 Answers

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

connsx(Xss, Xs) :-
   transpose(Xss, XssT),
   append(XssT, Xs).
like image 138
false Avatar answered Sep 28 '22 15:09

false