Prolog实现1-10偶数打印:调用printn(1)返回false求助
Fixing Your Prolog Even Number Printer
Let's break down why your current code returns false when you query ?- printn(1), then fix it step by step.
What's Wrong with the Original Code?
Your code has two key issues that lead to the false result:
- No fallback for odd starting values: When you call
printn(1), the first clause (printn(10)) doesn't match. The second clause checks ifX mod 2 =:= 0—since 1 is odd, this condition fails, and there's no logic to move to the next number. The clause just fails, leaving no other rules to try, so Prolog returnsfalse. - Limited termination condition: Your only stop case is
printn(10), but if you don't reach 10 via valid recursion steps (like starting at 1 and not handling odds), you never hit that termination rule.
Here's your original code for reference:
printn(10):- write(10). printn(X):- (X mod 2 =:= 0 -> write(X), Next is X+1, nl, printn(Next)).
Corrected Code
We need to add logic to handle odd numbers (by moving to the next number without printing) and a clear termination condition for when we exceed 10. Here's a robust version:
% Termination rule: stop when X is greater than 10 printn(X) :- X > 10, !. % Print even numbers, then recurse to the next value printn(X) :- X mod 2 =:= 0, write(X), nl, Next is X + 1, printn(Next). % Skip odd numbers, just recurse to the next value printn(X) :- X mod 2 =\= 0, Next is X + 1, printn(Next).
If you prefer a more concise approach using an if-else structure, this works too:
printn(X) :- X > 10, !. printn(X) :- (X mod 2 =:= 0 -> write(X), nl ; true), % Print even, do nothing for odd Next is X + 1, printn(Next).
How It Works
- Termination first: The first rule checks if
Xis greater than 10—if so, we stop (the!cut prevents unnecessary backtracking, keeping the execution clean). - Even number handling: If
Xis even, we print it, incrementX, and continue the recursion. - Odd number handling: If
Xis odd, we just incrementXand recurse without printing, ensuring we keep moving towards 10.
Now when you run ?- printn(1), you'll get the expected output:
2 4 6 8 10 true
内容的提问来源于stack exchange,提问作者Hadeer El-Zayat
相关产品推荐
相关产品推荐

