Loopi returning variables values (needed for python consulting later displaying the values)

Good afternoon,

For project purpose, I need to create a chat with the user, then save a music genre based on an emotion the user will type. I came up with this simple solution:

%suggested musical genre based on emotions
genre(['jazz,classical'],M) :- M = sad.
genre(['pop,rock'],M) :- M = happy.
genre(['haevy metal,hard rock'],M) :- M = angry.


chat(G) :- 
	write('How do you feel?'),
	read(M),
	genre(G,M).

Idea: the predicate genre simply tells what kind of genre is suggested based on an emotion (i.e, if the user types ‘sad’, the variable G must be equal to ['jazz, classical']).

Having said this, I need also to include the chat(G) predicate in a loop. Now, I tired to do the classical solution using this peace of code:

loop(0,G).
loop(N,G) :-
       chat(G),
       loop(N1,G1),
       N1 is N-1,
       not(G1=G).

but in this case I came up with errors and, if working, the values of G are not saved somewhere. I don’t know if I explained the problem correctly, I hope so. In short, I need to loop N times, over the chat(G) predicate and save all the values that the predicate genre(_,_) tells me. All for consult the prolog file with python, call the chat(G) predicate and save the values on a python list.

This type of question has been asked in various forms over the years on StackOverflow for the Prolog tag.

Here is an answer to one I gave a while ago that is similiar.

As for using Prolog with Python I can only point you to

mqi – Python and Other Programming Languge Integration for SWI Prolog

1 Like

Thank you, after hours I came up with this solution:

chat :-
    % Respond will be read as a string and not as a term, so it needs "".
    ask("y").

ask("y") :-
     write('How do you feel?: '),
     read_string(user, "\n", "\r", End, E),
     suggest(emotion(E)),
     write("Continue: (y or n) "),
     read_string(user, "\n", "\r", End, Respond),
     ask(Respond).

% writing results into file
ask("n") :- 
    tell('output.txt'), 
    listing(genre/2),
    told.





suggest(emotion("sad")) :- assertz(genre(["jazz,classical"],emotion("sad"))).
suggest(emotion("happy")) :- assertz(genre(["pop,country"],emotion("happy"))).