How to represent an array in Prolog?

1

I'm doing a work in Prolog that basically consists of a search problem, there is a scenario in a two-dimensional environment and one must trace the path that a character must follow to reach the other. There are some obstacles and rules but my question 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|   |   |   |   |   |   |   |   |   |   |
    
asked by anonymous 23.10.2018 / 02:06

1 answer

0

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

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

However, other representations are possible. A list in Prolog is always a linked list , so to access the (m,n) element you would need to scroll through the first% with% elements to find the right list, and then the m elements of that list, to find the position it wants:

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 sufficient, but in others you may prefer an alternative representation, with faster access (but with 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, type:

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).
...

At the end of the day there is no pattern, you choose the representation that is easier and more logical for you to work, depending on the problem you are trying to solve.

    
27.11.2018 / 03:38