add_id_pairs([],_,R,R).
add_id_pairs([Key|T],LastX,AVL,Res) :-
(Key = (X,Y) -> true ; add_error_and_fail(add_id_pairs,'Not a relation element: ',Key)),
(X=Y -> AVL2=AVL /* must already be in closure1 result */
; (LastX==X -> AVL1=AVL ; avl_store((X,X),AVL,true,AVL1)), % already added
avl_store((Y,Y),AVL1,true,AVL2)
),
add_id_pairs(T,X,AVL2,Res).