Standard term order takes variables as syntactic objects only. As a consequence beside other problems, sort/2
breaks the common assumptions of a relational definition. Neither can answer substitutions be a guarantee for solutions nor are ground instances of the second argument sorted.
?- X = 1, sort([1,X],[1]).
X = 1.
?- sort([1,X],[1]). % generalization fails
false.
?- sort([1,X],[2,1]).
X = 2. % unsorted list succeeds
?- X = 2, sort([1,X],[2,1]). % answer substitution fails
false.
But even if we ignore declarative concerns we are still faced with the problem that variable ordering only remains constant during the creation of a sorted list. So depending on the "age" of a variable we get
?- _=X+Y, sort([X,Y],[2,1]).
X = 2, Y = 1.
?- _=Y+X, sort([X,Y],[2,1]).
Y = 2, X = 1.
and age may change over time, even relative age.
We really should be protected by all such erratic behavior.
What I have tried so far is a safe definition, which produces the very same type errors as sort/2
but produces instantiation errors when the list to be sorted is not ground. As long as no instantiation error occurs, the definition is perfect, indeed.
sort_si(List, Sorted) :-
sort(List, ISorted),
( sort([], [_|Sorted]) ; true ), % just to get the type_error
( ground(ISorted)
-> Sorted = ISorted
; throw(error(instantiation_error, _Imp_def))
).
?- sort_si([X,X],S).
caught: error(instantiation_error, _97) % unexpected; expected: S = [X]
?- sort_si([-X,+Y], S).
caught: error(instantiation_error, _97) % unexpected; expected: S = [+Y,-X]
?- sort_si([_,_], []).
caught: error(instantiation_error, _97) % unclear, maybe failure
My question is: How to improve in ISO Prolog upon this definition by reducing the number of unnecessary instantiation errors? Ideally, an instantiation error for sort_si(List, Sorted)
only occurs, when there are instances of the goal sort(List, Sorted)
with different outcome. An optimal number of instantiation errors is not required. Maybe the fact that the list ISorted
is sorted can be used to some degree.
And, also Sorted
might be considered as now there will be never unsorted ground lists solutions to Sorted
.