简体   繁体   中英

Prolog: Return a list of facts from a list of atoms

I highly doubt it is possible, but I'm wondering is there is a way to transform a list of atoms into a list of fact. It is assumed that there won't be repetition of atoms between two facts.

More precisely, say I have the following list of facts:

person(Mike, male, 33).
person(Frank, male, 24).
person(Julie, female, 25).

And I want to call

listFacts( [Mike, Frank], L).

Which should return,

L = [person(Mike, male, 33), person(Frank, male, 24)].

You are currently using variables (the tokens starting with uppercase letters). You must switch to constants (in this case, atoms): Mike -> mike

After that it's easy going, using setof/3 :

person(mike, male, 33).
person(frank, male, 24).
person(julie, female, 25).

listFacts( Names, List ) :-
   setof(person(Name,S,A), (member(Name,Names),person(Name,S,A)), List).  

Which means: Find answers for Name taken from Names for which a fact person(Name,S,A) exists and put a corresponding term person(Name,S,A) into a set (actually a list) called List .

And so:

?- listFacts([mike,frank],F).
F = [person(frank, male, 24), person(mike, male, 33)].

The variation which is existentially qualified also works:

listFacts( Names, List ) :-
   setof(person(Name,S,A), Name^(member(Name,Names),person(Name,S,A)), List). 

Properly, it should not as it is the same as:

listFacts( Names, List ) :-
   setof(person(_Name,S,A), subgoal(Names,S,A), List). 

subgoal(Names,S,A) :-
   member(Name,Names),
   person(Name,S,A).

and that gives us no info about the Name :

?- listFacts([mike,frank],F).
F = [person(_6478, male, 24), person(_6492, male, 33)].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM