You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改cold_flu.pl Prolog程序以识别非感冒流感病例?

我明白你的问题了——原程序在患者没有头痛症状时会直接崩溃失败,而不是友好地提示可能不是感冒或流感。这是因为原有的hypothesis/1谓词只定义了cold和flu两种情况,没有处理“都不符合”的兜底逻辑,而且verify/1里的失败提示也会干扰流程。

下面是修改后的完整代码,完美解决你的需求:

% Flu or cold identification example 
% Start with ?- go. 
go:- 
    (hypothesis(Disease) -> 
        (Disease = none -> 
            write('不太可能是感冒或流感'), nl
        ;
            write('I believe you have: '), write(Disease), nl
        )
    ),
    undo. 

% Hypothesis that should be tested 
hypothesis(cold):- cold, !. 
hypothesis(flu):- flu, !. 
hypothesis(none). % 兜底的假设,当前面的诊断都不匹配时触发

% Hypothesis Identification Rules 
cold :- 
    verify(headache), 
    verify(runny_nose), 
    verify(sneezing), 
    verify(sore_throat). 
flu :- 
    verify(fever), 
    verify(headache), 
    verify(chills), 
    verify(body_ache). 

/* how to ask questions */ 
ask(Question) :- 
    write('Does the patient have the following symptom: '), 
    write(Question), 
    write('? '), 
    read(Response), nl, 
    ( (Response == yes ; Response == y) -> 
        assert(yes(Question)) 
    ; 
        assert(no(Question)), 
        fail
    ). 

:- dynamic yes/1,no/1. 

/* How to verify something */ 
verify(S) :- 
    (yes(S) -> true ; 
     (no(S) -> fail ; 
      ask(S))). % 移除原有的失败提示,让输出更干净

/* undo all yes/no assertions */ 
undo :- retract(yes(_)),fail. 
undo :- retract(no(_)),fail. 
undo.

关键修改点说明:

  • 新增兜底假设:在hypothesis/1的最后添加hypothesis(none),当cold和flu的诊断条件都不满足时,程序会匹配这个兜底项,不会直接失败。
  • 优化主流程逻辑:修改go/0谓词,增加对none结果的判断,触发对应的友好提示;如果是感冒或流感则保留原有的诊断输出。
  • 清理冗余输出:移除verify/1中的write('failed'),避免不必要的混乱输出,让交互流程更顺畅。
  • 保留原有撤销机制:undo/0依然会清除所有之前的症状断言,确保每次运行程序都是全新的诊断流程。

现在测试场景:当你回答头痛为no时,cold和flu的条件都会失败,程序会自动匹配hypothesis(none),输出“不太可能是感冒或流感”后干净终止。

内容的提问来源于stack exchange,提问作者runnerpaul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:16:23