Prolog Recursion skipping same results

前端 未结 3 971
余生分开走
余生分开走 2020-12-04 02:28

My code runs but the problem is it shows the same results more than once. Here\'s my code:

disease(hiv,[sore_throat,headache,fever,rash]).
disease(pregnancy         


        
3条回答
  •  Happy的楠姐
    2020-12-04 02:48

    Your program has a pure core - or to stick to medical terms - a pure heart, but this is intertwined with cancerous I/O tissue! In this manner doing it right is very difficult, if not impossible. For example, as a minor error, your program fails for kevin. But you probably meant it to succeed. On the other hand, you will succeed for the mysterious mister []! Who is that?

    So lets separate the pure from the impure!

    The pure part in your program is about relating a list of symptoms to possible diagnoses. Your working assumption is that if there is one symptom which is part of the indications for a malady, we will diagnose that malady - just to be sure. So why not call this symptoms_diagnosis/2?

    symptoms_diagnosis(Symptoms, Diagnosis) :-
       member(Symptom, Symptoms),
       disease(Diagnosis, Indications),
       member(Symptom, Indications).
    
    ?- symptoms_diagnosis([sore_throat,fatigue,tiredness,rash], Diagnosis).
    Diagnosis = hiv ;
    Diagnosis = pregnancy ;
    Diagnosis = flu ;
    Diagnosis = flu ;
    Diagnosis = hiv ;
    false.
    

    Note that even without any further ado, we have less redundant solutions than in your original program. So how to get rid of the remaining redundant solutions? This does the trick:

    ?- setof(t,symptoms_diagnosis([sore_throat,fatigue,tiredness,rash], Diagnosis),_).
    Diagnosis = flu ;
    Diagnosis = hiv ;
    Diagnosis = pregnancy.
    

    So whenever you get redundant solutions, simply wrap a setof(t, ..., _) around your goal. You can use that whenever the answers are ground answers. That is, there is no variable left in the answer.

    Maybe you prefer to get the diagnosis in a list of its own?

    ?- setof(Diagnosis,symptoms_diagnosis([sore_throat,fatigue,tiredness,rash],Diagnosis),Diagnoses).
    Diagnoses = [flu, hiv, pregnancy].
    

    So, now we are ready for the Princeton-Plainsboro Teaching Hospital! It is only superstition if Dr. House will not accept Prolog's diagnosis!

    For the impure part, please look at @Mog's approach.

提交回复
热议问题