Search code examples
prologpredicatemaze

Prolog saying if something in a list (in this case grid/1) is white. Prolog


I am new to prolog and wanted to know if you have a maze with certain ''pixels''. How could you implement a predicate white/1, which says if the pixel is a white one or a black one. The problem that I have is that I want to make a predicate, that if I query ?- white(3/3). it should return true. This is my database:

grid([ [w, w, w, b, w],
[b ,b, w, w, w],
[w, w, w, b, w],
[w, b, b, b, b],
[w, w, w, w, w] ]).

Thanks for the answer, I implemented this program:

white(X/Y) :-
    nth1(X/Y, grid, _).

But after implementing this program I still get a false.


Solution

  • white(X/Y) :-
        grid(M),
        nth1(X, M, Line),
        nth1(Y, Line, w).
    

    The first nth1 get the row, and the second one gets the element of the row.

    I suggest playing with the query

    ?- grid(M), nth1(X, M, Line), nth1(Y, Line, Cell).
    
    Cell = w
    Line = [w,w,w,b,w]
    M = [[w,w,w,b,w],[b,b,w,w,w],[w,w,w,b,w],[w,b,b,b,b],[w,w,w,w,w]]
    X = 1
    Y = 1 ? ;
    
    Cell = w
    Line = [w,w,w,b,w]
    M = [[w,w,w,b,w],[b,b,w,w,w],[w,w,w,b,w],[w,b,b,b,b],[w,w,w,w,w]]
    X = 1
    Y = 2 ? ;
    
    Cell = w
    Line = [w,w,w,b,w]
    M = [[w,w,w,b,w],[b,b,w,w,w],[w,w,w,b,w],[w,b,b,b,b],[w,w,w,w,w]]
    X = 1
    Y = 3 ? ;
    
    Cell = b
    Line = [w,w,w,b,w]
    M = [[w,w,w,b,w],[b,b,w,w,w],[w,w,w,b,w],[w,b,b,b,b],[w,w,w,w,w]]
    X = 1
    Y = 4 ? ;
    

    Just press ; after each solution and prolog will iterate through every possible X, Y for your maze. You can get a feeling of how nth1 is accessing the cell.

    In general I would advise that you use two explicit parameters such as white(X, Y) unless there is a good reason to use X/Y.