Anyone knows why this keeps failing?
foo :- write('3 numbers: '),
read(A),
read(B),
read(C),
(A > B,B > C,write(A),tab(1),write(B),tab(1),write(C));
(A > C,C > B,write(A),tab(1),write(C),tab(1),write(B));
(B > A,A > C,write(B),tab(1),write(A),tab(1),write(C));
(B > C,C > A,write(B开发者_运维技巧),tab(1),write(C),tab(1),write(A));
(C > B,B > A,write(C),tab(1),write(B),tab(1),write(A));
(C > A,A > B,write(C),tab(1),write(B),tab(1),write(A)).
Is a prolog function to print 3 input numbers in order. I keep getting this error:
uncaught exception: error(instantiation_error,(>)/2)
I think it would be better if you didn't write everything into one clause. Not only would that make your code more readable, but you also wouldn't make this mistake.
The problem is that your code is parsed something like this:
(read AND read AND read AND test) OR test OR test OR …
This means that A
, B
and C
have value only in the first test. And >
requires both arguments to have a value. To fix this, you can use parentheses:
foo :- write('3 numbers: '),
read(A),
read(B),
read(C),
((A > B,B > C,write(A),tab(1),write(B),tab(1),write(C));
(A > C,C > B,write(A),tab(1),write(C),tab(1),write(B));
(B > A,A > C,write(B),tab(1),write(A),tab(1),write(C));
(B > C,C > A,write(B),tab(1),write(C),tab(1),write(A));
(C > B,B > A,write(C),tab(1),write(B),tab(1),write(A));
(C > A,A > B,write(C),tab(1),write(B),tab(1),write(A))).
Use a true if-then-else:
(A > B, B > C ->
write(A),tab(1),write(B),tab(1),write(C)
; A > C, C > B ->
write(A),tab(1),write(C),tab(1),write(B)
; B > A, A > C ->
write(B),tab(1),write(A),tab(1),write(C)
; % etc
精彩评论