Getting list of solutions in Prolog -


i learning prolog , reading book called programming prolog artificial intelligence. practice want learn how extend 1 of examples in book. can please help?

say have these facts:

parent(pam, bob). %pam parent of bob parent(george, bob). %george parent of bob 

how write prolog predicate give me list of bobs parents? example:

list_parents(bob, l).  l = [pam, george] ; l = [george, pam] ; true. 

an all-solutions predicate findall/3 might trick:

list_parents(p, l) :-     findall(parent, parent(parent, p), l). 

simply put, findall/3 finds bindings parent in 'backtrack-able' goal parent(parent, p), , puts bindings of parent list l. note won't remove duplicates, can sort/2 l before returning create set. executing this:

?- list_parents(bob, l). l = [pam, george]. 

if don't have findall/3 in prolog implementation, manually this:

list_parents(p, l) :-     list_parents(p, [], l).  list_parents(p, acc, l) :-     parent(parent, p),     \+ member(parent, acc), !,     list_parents(p, [parent|acc], l).  list_parents(_, l, l). 

this version sends calls list_parents/2 off accumulator-version, list_parents/3. latter tries collect parent bindings also, long haven't seen them before (hence \+ member check), , returns list no new parent bindings accumulated acc list can found. executing gives same result first option:

?- list_parents(bob, l). l = [pam, george]. 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -