I have found that
arg/3 simply fails when the index is out of range. I changed related codes. I believed that it raises out-of-range exception when it is. Here are related new and old style of using
arg/3, new one is more natural in that index is increasing, but the old one is decreasing. Also new one can be used without knowing the arity of the term. I like it.
% NEW style % ?- unify_args(1, f(A, B, C), a). %@ A = B, B = C, C = a. unify_args(I, X, A):- arg(I, X, A), !, J is I + 1, unify_args(J, X, A). unify_args(_, _, _). % OLD style % ?- old_unify_args(3, f(A, B, C), a). %@ A = B, B = C, C = a. old_unify_args(0, _, _):-!. old_unify_args(I, X, A):- arg(I, X, A), !, J is I - 1, old_unify_args(J, X, A).