S_Dimitrov
S_Dimitrov

Reputation: 41

Prolog simple predicate , How?

I have a predicate:

neig(I, J, I1, J1):-
    I1 is I - 1,
    I1 >= 0,
    J1 is J.
neig(I, J, I1, J1):-
    I1 is I + 1,
    not(I1 > 8),
    J1 is J.
neig(I, J, I1, J1):-
    J1 is J - 1,
    J1 >= 0,
    I1 is I.
neig(I, J, I1, J1):-
    J1 is J + 1,
    not(J1 > 8),
    I1 is I.

neig(I, J, I1, J1):-
    I1 is I - 1,
    J1 is J - 1,
    I1 >= 0,
    J1 >= 0.
neig(I, J, I1, J1):-
    I1 is I + 1,
    J1 is J + 1,
    not(I1 > 8),
    not(J1 > 8).
neig(I, J, I1, J1):-
    I1 is I + 1,
    J1 is J - 1,
    J1 >= 0,
    not(I1 > 8).
neig(I, J, I1, J1):-
    I1 is I - 1,
    J1 is J + 1,
    I1 >= 0,
    not(J1 > 8).

How to write predicate all_neighs(I, J, L) where L is as list and it contains all different elements [I1, J1], such that neigh(I, J, I1, J1)?

Upvotes: 4

Views: 250

Answers (1)

PeterT
PeterT

Reputation: 8284

I think that you need this build-in predicate.

findall(Things,GoalCondition, Bag)

Which would then look something like this:

all_neighs(I,J,L) :- findall([H|T],neig(I,J,H,T), L).

you may have to check if T is an atom if that's what you want. But with this my result with some examples.

1 ?- all_neighs(0,0,X).
X = [[1|0], [0|1], [1|1]].

2 ?- all_neighs(1,1,X).
X = [[0|1], [2|1], [1|0], [1|2], [0|0], [2|2], [2|0], [0|...]].

You should also take a look at this: [1] it explains on how you can easily implement the findall(...) predicate yourself.

[1] http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/2_12.html

Upvotes: 1

Related Questions