Home > Blockchain >  Turn Nested list to a list of lists PROLOG
Turn Nested list to a list of lists PROLOG

Time:05-03

i need some help with this, i have a list of this kind:

[[[4,11,9,7],[4,13,8,6],[4,12,10,5]],[[3,12,8,7],[3,11,10,6],[3,13,9,5]],[[2,13,10,7],[2,12,9,6],[2,11,8,5]]] %(is a list with three lists, and inside of each list are other three list)

And i´m trying to get one like this:

[[4,11,9,7],[4,13,8,6],[4,12,10,5],[3,12,8,7],[3,11,10,6],[3,13,9,5],[2,13,10,7],[2,12,9,6],[2,11,8,5]] %(a list with nine lists).

%Currently i have this kind of append, but the output isn't near what i need:

appendL([],[]).  %->base case
appendL([H], H). %->base case
appendL([H,H2|T], [L3|L1]):-
    append(L,L1,L3),
    append(H,H2,L),
    appendL(T, L1).

This one give: [[[4,11,9,7],[4,13,8,6],[4,12,10,5],[3,12,8,7],[3,11,10,6],[3,13,9,5],[2,13,10,7],[2,12,9,6],[2,11,8,5]],[2,13,10,7],[2,12,9,6],[2,11,8,5]]

And you can notice that there is three list that appears two times

CodePudding user response:

Can use DCG as per Get elements from list of lists

seq([]) --> [].
seq([E|Es]) --> [E], seq(Es).

seqq([]) --> [].
seqq([Es|Ess]) --> seq(Es), seqq(Ess).

Result in swi-prolog:

% Show first 99 elements of a list
?- set_prolog_flag(answer_write_options, [quoted(true), portray(true), max_depth(100), attributes(portray)]).

?- phrase(seqq([[[4,11,9,7],[4,13,8,6],[4,12,10,5]],[[3,12,8,7],[3,11,10,6],[3,13,9,5]],[[2,13,10,7],[2,12,9,6],[2,11,8,5]]]), L), length(L, Len).
L = [[4,11,9,7],[4,13,8,6],[4,12,10,5],[3,12,8,7],[3,11,10,6],[3,13,9,5],[2,13,10,7],[2,12,9,6],[2,11,8,5]],
Len = 9.

Note: If not wanting to use DCG, then should use a difference list instead of append/2, as per https://www.swi-prolog.org/pldoc/man?predicate=flatten/2

CodePudding user response:

Guess what, append(K,X). Make the work where;

K=[[[4,11,9,7],[4,13,8,6],[4,12,10,5]],[[3,12,8,7],[3,11,10,6],[3,13,9,5]],[[2,13,10,7],[2,12,9,6],[2,11,8,5]]]
X= [[4,11,9,7],[4,13,8,6],[4,12,10,5],[3,12,8,7],[3,11,10,6],[3,13,9,5],[2,13,10,7],[2,12,9,6],[2,11,8,5]]
  • Related