How to represent a matrix in Prolog?

Asked

Viewed 276 times

1

I am doing a work on Prolog that consists basically of a search problem, there is a scenario in a two-dimensional environment and one must trace the path that one character must follow to get to the other. There are some obstacles and rules but my doubt initially is about how to represent this environment:

Environment 5 x 10 squares

 | A | B | C | D | E | F | G | H | I | J |
 |---|---|---|---|---|---|---|---|---|---|
1|   |   |   |   |   |   |   |   |   |   |
2|   |   |   |   |   |   |   |   |   |   |
3|   |   |   |   |   |   |   |   |   |   |
4|   |   |   |   |   |   |   |   |   |   |
5|   |   |   |   |   |   |   |   |   |   |

1 answer

1


The most common way to represent matrices in programming languages that do not have a native type is through a list of lists:

ambiente([[_,_,_,_,_,_,_,_,_,_], [_,_,_,_,_,_,_,_,_,_], ... [_,_,_,_,_,_,_,_,_,_]]).

However, other representations are possible. A Prolog list is always a chain list, so that to access the element (m,n) you would need to go through the first m elements to find the right list, and then the n elements of that list to find the position you want:

posicao(0,N,[Cabeca|_],E) :-
    posicao_lista(N,Cabeca,E).
posicao(M,N,[_|Cauda],E) :-
    M1 is M - 1,
    posicao(M1,N,Cauda,E).

posicao_lista(0,[X|_],X).
posicao_lista(N,[_|R],X) :-
    N1 is N - 1,
    posicao_lista(N1,R,X).

In some cases this may be enough, but in others you may prefer an alternative representation, with faster access (but more difficult modification). If your environment is immutable, an alternative would be to explicitly list what you have in each cell, through a series of isolated facts. For example:

celula(0,0,x).
celula(0,1,y).
celula(0,2,z).
...
celula(0,9,w).
celula(1,0,a).
celula(1,1,b).
...
celula(4,9,o).

Other intermediate representations are also possible, like:

linha(0, a, b, c, d, e, f, g, h, i, j). /* Substitua a,b,etc pelo valor da célula */
linha(1, a, b, c, d, e, f, g, h, i, j).
...

In the end there is no standard, you choose the representation that is easier and more logical for you to work, according to the problem you are trying to solve.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.