使用swi-prolog从用户输入创建列表

时间:2015-07-29 20:11:56

标签: list prolog

这是我第一次体验Prolog。我正处于编写程序的开始阶段,该程序将从用户(症状)获取输入并使用该信息来诊断疾病。我最初的想法是创建列表头部疾病名称和尾部症状的列表。然后提示用户输入症状并使用用户输入创建列表。然后比较列表以查看尾部是否匹配。如果尾部匹配,那么我创建的列表的头部将是诊断。首先,我将该计划缩减为仅有三种疾病,只有一些症状。在我开始比较之前,我需要使用从用户读取的值来构建列表的尾部,但我似乎无法使语法正确。

这是我到目前为止所做的:

disease([flu,fever,chills,nausea]).
disease([cold,cough,runny-nose,sore-throat]).
disease([hungover,head-ache,nausea,fatigue]).

getSymptoms :-
    write('enter symptoms'),nl,
    read(Symptom),
    New_Symptom = [Symptom],
    append ([],[New_symptom],[[]|New_symptom]),
    write('are their more symptoms? y or n '),
    read('Answer'),
    Answer =:= y
    -> getSymptoms
    ; write([[]|New_symptom]).

附加行发生错误。语法错误:操作员预期。  任何有关此错误或程序设计的帮助都将非常感激。

2 个答案:

答案 0 :(得分:1)

这是阅读症状列表的一种方法:

getSymptoms([Symptom|List]):-
    writeln('Enter Symptom:'),
    read(Symptom),
    dif(Symptom,stop),
    getSymptoms(List).

getSymptoms([]).

你输入停止。如果你想完成清单。

然后,您需要确定您希望与您代表疾病的方式相匹配的逻辑。

一个完整的例子:

:-dynamic symptom/1.

diagnose(Disease):-
    retractall(symptom(_)),
    getSymptoms(List),
    forall(member(X,List),assertz(symptom(X))),
    disease(Disease).



getSymptoms([Symptom|List]):-
    writeln('Enter Symptom:'),
    read(Symptom),
    dif(Symptom,stop),
    getSymptoms(List).

getSymptoms([]).



disease(flue):-
    symptom(fever),
    symptom(chills),
    symptom(nausea).

disease(cold):-
   symptom(cough),
   symptom(runny_nose),
   symptom(sore_throat).

disease(hungover):-
   symptom(head_ache),
   symptom(nausea),
   symptom(fatigue).

答案 1 :(得分:0)

create(L1):-read(Elem),create(Elem,L1)。

create(-1,[]):-!。 create(Elem,[Elem | T]):-read(Nextel),create(Nextel,T)。

go:-write('创建列表'),nl,      写('输入-1停止'),nl,      创建(L)      write('List is:'),      写(L)。

相关问题