how to transform a structure matrix to a list matrix in prolog

0

I have this entry in Prolog and I ask for the function x

X((1,0,1,0),(1,0,1,0))

and I want to get it out

[[1,0,1,0],[1,0,1,0]]

how could I do?

I know that the function univ converts me to list and vice versa but if I put X((1,0,1,0)) =.. Lista it returns [X,(1,0,1,0)] and it does not help me

    
asked by Efrainrodc 10.07.2017 в 01:42
source

1 answer

1

First you must create a predicate that converts a row into a list. To do this, with =../2 you can take an element of the tuple and recursively try the queue:

row_to_list(X, [X]) :- number(X).
row_to_list(X, [H|S]) :- X =.. [_,H|[T]], row_to_list(T,S).

Now the list of rows must be treated, applying the previous predicate to each row:

rows_to_list([],[]).
rows_to_list([X|Xs], [Y|Ys]) :- row_to_list(X,Y), rows_to_list(Xs,Ys).

Finally, the main predicate must transform the structure x((...),(...),...) is a list and transform the rows using the previous predicate:

matrix_to_list(X,S) :- X =.. [_|T], rows_to_list(T,S).

For example:

?- matrix_to_list(x((1,0,1,0),(1,0,1,0)),X).
X = [[1, 0, 1, 0], [1, 0, 1, 0]] ;
false.

If you use an interpreter such as SWI-Prolog, you could use the maplist/3 predicate and save yourself the definition of rows_to_list/2 :

matrix_to_list(X,S) :- X =.. [_|T], maplist(row_to_list,T,S).
    
answered by 11.07.2017 в 03:53