Prolog偏好评估程序控制台双输入功能故障排查请求
Let's tackle your problem step by step—your core issue is that the start/0 predicate isn't handling user input correctly, and there's also a subtle bug in your reverse preference rule that could cause unexpected behavior or infinite recursion.
First, Fix the Reverse Preference Rule
Your current reverse rule has two critical issues:
preferencia(X,Y,D):-preferencia(Y,X,D),!. % reverse preferenciaance
- Logical mistake: If Ana prefers Maria with a value of 1, Maria should logically prefer Ana with -1, not the same value.
- Infinite recursion risk: If no direct preference exists between two people, this rule will keep calling itself back and forth forever.
Replace it with this corrected version:
preferencia(X, Y, D) :- preferencia(Y, X, RevD), D is -RevD, !.
This ensures reverse preferences are the negative of the original, and the cut (!) prevents unnecessary backtracking that could lead to loops.
Fix the start/0 Predicate
Your original start only reads one input value and passes an invalid list structure to eval/2. We need to capture two names from the user and feed them correctly to your evaluation function. Here are two working options:
Option 1: Single Comma-Separated Input
Let users enter both names in one line (e.g., rui, maria):
start :- write('Pick 2 Persons to make a group (e.g., rui, maria): '), read((Name1, Name2)), % Reads the comma-separated pair as a compound term eval([Name1, Name2], DS), write('Preference value: '), write(DS), nl. % Adds a newline for readability
Option 2: Two Separate Inputs
Let users enter one name, press enter, then enter the second:
start :- write('Enter first person: '), read(Name1), write('Enter second person: '), read(Name2), eval([Name1, Name2], DS), write('Preference value: '), write(DS), nl.
Why This Works
- Both versions correctly capture two names from the user, no unbound variables left hanging.
- We pass the list
[Name1, Name2]directly toeval/2, which matches your working static test call (eval([rui,maria],DS)). - The fixed reverse rule ensures that even if there's no direct preference fact for a pair (like Maria to Ana), the program will compute the inverse correctly instead of looping.
Test It Out
If you run start and input rui, maria, the program will return Preference value: 1—just like your static test. If you input maria, rui, it will return -1 (thanks to the fixed reverse rule), which aligns with logical preference symmetry.
内容的提问来源于stack exchange,提问作者Macronaldo

