Search code examples
prolog

How to iterate through the predicates in Prolog


I'm new to prolog, but basically, I want a program to iterate through the predicates(not sure if I'm using that term correctly) and then come to a final predicate which can process the input and provide one of two answers. The ask and the maplist were my tries at iterating through the program the way a program like Java would. (Also, sidenote, but is there any way to have the user input Yes and No instead of true. and false.?) Here's how my code looks currently:

ask(happy,X).
ask(lonely,X).
ask(education,X).
ask(institution,X).
ask(home,X).
ask(parents,X).
ask(social_life,X).
ask(hobbies,X).
ask(opinion,X).
ask(relationship,X).
ask(finances,X).
ask(future,X).
ask(freedom,X).
ask(feelings,X).

maplist(ask(_), Xs).


Xs= [happy(X),lonely(X),education(X),institution(X), home(X),
parents(X), social_life(X), hobbies(X), opinion(X), relationship(X),
finances(X), future(X), freedom(X),feelings(X)].

happy(X):-
     write("Are you happy?"),nl,
     read(X).

lonely(X):-
     write("Are you lonely?"),nl,
     read(X). 

Solution

  • Maybe this can serve as inspiration

    main(AnswersOut) :-
       Ls = [happy,lonely,education],
       ask_next_question(Ls,[],AnswersOut).
    
    ask_next_question([L|Ls],Answers,AnswersOut) :-
       format("Question about: ~w\n",[L]),
       read_line_to_string(user_input,Str),
       format("You said: ~w\n",[Str]),
       ask_next_question(Ls,[L-Str|Answers],AnswersOut).
    
    ask_next_question([],A,A).
    

    Then you can collect answers into a list of pairs for further processing. Note the use of read_line_to_string/2 which doesn't read a term (necessarily terminated with .) as read/2 does, but an arbitrary String terminated by newline.

    Run it:

    ?- main(A).
    Question about: happy
    |: Well....
    You said: Well....
    Question about: lonely
    |: Yes
    You said: Yes
    Question about: education
    |: Too high
    You said: Too high
    A = [education-"Too high", lonely-"Yes", happy-"Well...."].