1
votes

I don't know how should I describe this case.. So I don't know what keywords I can to search. I believe this is not a hard question.

I'm trying to solve a graph problem search in Prolog. say I have the follow predicts:

bot(A,P,R):- ...
right(A,P,R):- ...

where A is the graph, p is the current point, and R would be the bottom/right point, accordingly. They'll fail when there's no such point. (for example, there's no point on my right, so it will fail when I call right)

Now I want to have a list, which has my bottom and right neighbours. So I want is something like this:

getRightAndBotNeighbour(A,P,Neighbours):-
  ( bot(A,P,BT)  -> B = [BT] ; B = []), 
  ( right(A,P,RT)-> R = [RT] ; R = []), 
  append(B,R,Neighbours).

The code above actually works.. but that looks ugly to me. I want to know if there're something like.. 1 line solution?

Thanks a lot.

1

1 Answers

2
votes

A slight simplification of your code:

getRightAndBotNeighbour(A,P,Ns):-
   ( bot(A,P,BT)   -> Ns = [BT|Ns1] ; Ns = Ns1 ), 
   ( right(A,P,RT) -> Ns1 = [RT] ; Ns1 = [] ).

It would look neater if you had variants of bot/3 and right/3 that put their result directly into a list:

getRightAndBotNeighbour(A,P,Ns):-
   bot(A, P, Ns, Ns1),
   right(A, P, Ns1, []).

bot(A, P, Ns, Ns1) :-       % right/4 analogous
   ( bot(A, B, T) -> Ns = [T|Ns1] ; Ns = Ns1 ).

And finally, a (completely different) one-line solution would be

getRightAndBotNeighbour(A,P,Ns):-
   findall(T, (bot(A,P,T) ; right(A,P,T)), Ns)