简体   繁体   中英

Creating a list from user input with swi-prolog

This is my first experience with Prolog. I am at the beginning stages of writing a program that will take input from the user (symptoms) and use that information to diagnose a disease. My initial thought was to create lists with the disease name at the head of the list and the symptoms in the tail. Then prompt the user for their symptoms and create a list with the user input. Then compare the list to see if the tails match. If the tails match then the head of the list I created would be the diagnosis. To start I scaled the program down to just three diseases which only have a few symptoms. Before I start comparing I need to build the tail of list with values read from the user but I can't seem to get the syntax correct.

This is what I have so far:

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

The error occurs on the append line. Syntax Error: Operator Expected. Any help with this error or the design of the program in general would be greatly appreciated.

This is one way to read a list of symptoms in:

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

getSymptoms([]).

You type stop. when you want to finish the list.

You would then need to decide what logic you want to match the way you have represented a disease.

A complete example:

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

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

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

go:- write('Creating a list'),nl, write('Enter -1 to stop'),nl, create(L), write('List is:'), write(L).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM