Question

Say I have the following piece of code:

edge(a, b).
edge(a, c).
edge(a, d).

Now when I do

neighbors(V, N) :- edge(V, N), writeln(N), fail. 

I can get a list of the neighbors printed out to the console. But how can I get it as a result list? Something like

neighbors(V, Vs)  :- 
    edge(V, N),
    not(member(N, Vs)),
    neighbors(V, [N|Vs]).

(the above piece doesn't really work due to the way member is handled. Any suggestion please?

Was it helpful?

Solution

You can use bagof/3 to create a list of your verticies that satisfy the goal, "Vs is all N that is an edge of V."

neighbors(V, Vs) :- bagof(N, edge(V, N), Vs).

neighbors(a, Vs). % Vs = [b, c, d].

OTHER TIPS

Read about findall, bagof and setof in your favorite Prolog implementation's manual, or e.g. the section "11.2 Collecting solutions" in Learn Prolog Now! (Unfortunately it is difficult to directly link to these resources.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top