【问题标题】:How to iterate through the predicates in Prolog如何遍历 Prolog 中的谓词
【发布时间】:2020-06-10 20:53:49
【问题描述】:

我是 prolog 的新手,但基本上,我想要一个程序来遍历谓词(不确定我是否正确使用了该术语),然后得出一个可以处理输入并提供其中一个的最终谓词两个答案。 ask 和 maplist 是我尝试像 Java 这样的程序那样迭代程序。 (另外,旁注,但有没有办法让用户输入是和否而不是真。和假。?) 这是我的代码目前的样子:

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). 

【问题讨论】:

  • 提示:使用main 谓词。

标签: prolog


【解决方案1】:

也许这可以作为灵感

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).

然后,您可以将答案收集到一个配对列表中以供进一步处理。 请注意read_line_to_string/2 的使用,它不会像read/2 那样读取term(必须以. 终止),而是以换行符终止的任意字符串。

运行它:

?- 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...."].

【讨论】:

  • 谢谢,您帮我解决了 2 个问题。不过,还有更多:您说我可以将答案收集成一组以进行进一步处理,我假设使用Str 变量。对我可以做的处理类型有任何想法(我在想自然语言,但我怀疑这是否可行。)另外,有没有办法可以处理它们以最终达到三个判决之一?谢谢。
  • @Biscuit 在上面的示例中,A 包含以Keyword-Value 对形式的一个用户的响应(它们只是实际上看起来像-(Keyword,Value) 的术语)。您的“判决”谓词必须检查A。这是一个可能的处理顺便说一句。收集许多用户响应(可能将它们存储在(易失性!)Prolog database)最后,在 Prolog 顶层使用 library(aggregate) 进行统计
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
相关资源
最近更新 更多