How to create a list from facts in Prolog?
16,597
Solution 1
Using findall/3
:
people(L) :- findall(X, (man(X) ; woman(X)), L).
?- people(X).
X = [john, carl, mary, rose].
Solution 2
person(anne).
person(nick).
add(B, L):-
person(P),
not(member(P, B)),
add([P|B], L),!.
add(B, L):-
L = B,!.
persons(L):-
add([], L).
Author by
renatov
Languages: Python, C, Prolog, PHP, MySQL, HTML, CSS, Javascript.
Updated on June 20, 2022Comments
-
renatov almost 2 years
There are these facts:
man(john). man(carl). woman(mary). woman(rose).
I need to create the predicate people(List), which returns a list with the name of every man and woman based on the previous facts. This is what I need as output:
?- people(X). X = [john, carl, mary, rose]
And here is the code I wrote, but it's not working:
people(X) :- man(X) ; woman(X). people(X|Tail) :- (man(X) ; woman(X)) , people(Tail).
Could someone please help?
-
Will Ness over 4 yearsHi, I've reverted your edit to the question since it changed the question too much, drastically altering its meaning and invalidating an existing answer. You can add your understanding of the question's intentions into your answer here. :) Cheers, and +1.
-
Михаил Беляков over 4 yearsHi, as far as I know, Prolog is a language, that has more academical than practical usage. The most often situation when someone has an interest in this language is when students make their exercices whith it. Tasks, that they get from their tutors, in most cases directed to learn common conceptions (recursion, for example), not to use easy ways (functions, prepared by someone else). I think, that typical one who will see this topic will be a student with "recursion headache", not one, who is unable to read about method findall in Prolog documentation.
-
Will Ness over 4 yearsI fully agree with you about doing it yourself, not just using ready-made library functions, to learn the language. this is totally orthogonal to the issue of the edit though. As the ways of SO go, we are not allowed to make drastic changes to questions invalidating the existing answers. as I said, you could add those clarifications into your answer, it would only add value to it IMO. :)
-
Михаил Беляков over 4 yearsThank you in any case, Will. I understand this policy, it's allright. It was pleasant for me to solve a Prolog exercise. I went here to find solution, but eventually have solved the task by myself. Sharing knowledge on Stackoverflow is fun :)
-
Raj over 3 yearsHow can we convert list to facts ? Example: I have list as Rows = [num('', 'A', 'B', 'C'), num('A', -, 4, 5), num('B', 8, -, 6), num('C', 2, 3, -)]. How can I extract facts from it ? So, that when I write ?-num('A',X,Y,Z). I should get the result.