Standard term order (ISO/IEC 13211-1 7.2 Term order) is defined over all terms — including variables. While there are good uses for this — think of the implement
This answer follows up on my previous one which presented safe_term_less_than/2.
What's next? A safe variant of compare/3—unimaginatively called scompare/3:
scompare(Ord, L, R) :-
i_scompare_ord([L-R], Ord).
i_scompare_ord([], =).
i_scompare_ord([L-R|Ps], X) :-
when((?=(L,R);nonvar(L),nonvar(R)), i_one_step_scompare_ord(L,R,Ps,X)).
i_one_step_scompare_ord(L, R, LRs, Ord) :-
( L == R
-> scompare_ord(LRs, Ord)
; term_itype(L, L_type),
term_itype(R, R_type),
compare(Rel, L_type, R_type),
( Rel \== (=)
-> Ord = Rel
; compound(L)
-> L =.. [_|Ls],
R =.. [_|Rs],
phrase(args_args_paired(Ls,Rs), LRs0, LRs),
i_scompare_ord(LRs0, Ord)
; i_scompare_ord(LRs , Ord)
)
).
The predicates term_itype/2 and args_args_paired//2 are the same as defined previously.