Prolog院校推荐程序异常:无论是否匹配均显示无推荐结果
Prolog院校推荐程序修复方案
问题根源
当前程序的query_university谓词使用;(逻辑或)连接两个分支,Prolog在执行完第一个分支(输出匹配院校)后会自动回溯尝试第二个分支,导致无论是否有匹配结果,最终都会显示"Sorry, there are no recommended Universities"。这是因为;会让Prolog遍历所有可能分支,而非仅在第一个分支失败时才执行第二个。
修复步骤
使用findall/3收集所有符合条件的院校结果,先判断结果列表是否为空,再针对性输出内容,避免回溯导致的错误提示:
- 收集所有匹配的院校信息到列表中
- 检查列表状态:
- 列表非空:遍历输出每一所推荐院校
- 列表为空:输出无推荐提示
修改后的完整代码
university(a60, 'Anglia Ruskin University', 'Eastern', 14200, 'www.anglia.ac.uk'). university(b22, 'University of Bedfordshire', 'Eastern', 9900, 'www.beds.ac.uk'). university(e14, 'University of East Anglia', 'Eastern', 10500, 'www.uea.ac.uk'). university(e70, 'The University of Essex', 'Eastern', 14450, 'www.essex.ac.uk'). program(computer_science, a60, graduate). program(computer_science, b22, graduate). program(computer_science, e14, undergraduate). program(computer_science, e70, undergraduate). program(math, a60 , graduate). program(math, b22, graduate). program(math, e14, undergraduate). recommend_university(UcasCode, Degree, Location, TuitionLower, TuitionUpper, Program, University) :- university(UcasCode, University, Location, Tuition, _), program(Program, UcasCode, Degree), Tuition >= TuitionLower, Tuition =< TuitionUpper. query_university :- write('Please enter the location: '), read(Location), write('Please enter the tuition range lower bound: '), read(TuitionLower), write('Please enter the tuition range upper bound: '), read(TuitionUpper), write('Please enter the program of study: '), read(Program), write('Please enter the level of study (undergraduate or graduate): '), read(Degree), % 收集所有符合条件的大学 findall(University, recommend_university(_, Degree, Location, TuitionLower, TuitionUpper, Program, University), Universities), % 根据结果列表输出内容 ( Universities \= [] -> write('Recommended universities:'), nl, maplist(write_university, Universities) ; write('Sorry, there are no recommended Universities') ). % 辅助谓词:输出单个大学名称 write_university(University) :- write('- '), write(University), nl.
额外优化说明
- 移除冗余的
program_offered谓词,直接在recommend_university中调用program/3,减少不必要的谓词嵌套 - 添加
write_university辅助谓词,让输出格式更清晰(每个推荐院校前加短横线) - 使用
->(条件蕴含)替代;,确保仅在结果为空时才执行无推荐提示分支
内容的提问来源于stack exchange,提问作者Israel Amet
相关产品推荐
相关产品推荐

