Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rearranging variable_names

How to write in a standard conforming manner avs_term_rearranged(AVs, T, AVsR) with given AVs and T such that AVsR is a permutation of AVs with the elements arranged in same order as their variables occur in left-to-right order in T.

AVs is a list of elements of the form A = V where A is an atom designating a variable name like 'X' and V is a corresponding variable. Such lists are produced by read_term/2,3 with the read-option variable_names/1 (7.10.3). Additionally, the precise order of elements is not defined.

| ?- read_term(T,[variable_names(AVs)]). A+B+A+_+C.  AVs = ['A'=A,'B'=B,'C'=C] T = A+B+A+_+C 

T is a term that contains all variables of AVs plus some more.

Note that in a standard conforming program one cannot rely on the term order for variables (7.2.1):

7.2.1 Variable

If X and Y are variables which are not identical then X term_precedes Y shall be implementation dependent except that during the creation of a sorted list (7.1.6.5, 8.10.3.1 j) the ordering shall remain constant.

NOTE — If X and Y are both anonymous variables then they are not identical terms (see 6.1.2 a).

Consider as an example from 8.4.3.4:

sort([f(U),U,U,f(V),f(U),V],L).    Succeeds, unifying L with [U,V,f(U),f(V)] or    [V,U,f(V),f(U)].    [The solution is implementation dependent.] 

So there are two possible ways how sort/2 will work, and one cannot even rely on the success of:

sort([f(U),U,U,f(V),f(U),V],L), sort(L, K), L == K. 

As an example:

?- avs_term_rearranged(['A'=A,'B'=B,'C'=C], A+C+F+B, AVsR).    AVsR = ['A'=A,'C'=C,'B'=B]. 
like image 413
false Avatar asked Jan 23 '14 12:01

false


1 Answers

avs_term_rearranged(AVs, T, AVsR) :-     term_variables(T, Vs),     copy_term(Vs+AVs, Vs1+AVs1),     bind_names(AVs1),     build_vn_list(Vs, Vs1, AVsR).  bind_names([]). bind_names([N=V|AVs]) :-     N = V,     bind_names(AVs).  build_vn_list([], [], []). build_vn_list([V|Vs],[N|Ns],NVs) :-     ( atom(N) ->       NVs = [N=V|NVs1]     ; var(N) ->       NVs = NVs1     ),     build_vn_list(Vs, Ns, NVs1). 
like image 103
Per Mildner Avatar answered Sep 24 '22 22:09

Per Mildner