Maybe revert the occurs check also after G succeeds ?
with_occurs_check(G) :-
current_prolog_flag(occurs_check, F),
setup_call_cleanup(
set_prolog_flag(occurs_check, true),
(G, set_prolog_flag(occurs_check, F)),
set_prolog_flag(occurs_check, F)).
test run:
?- with_occurs_check((X=1;X=2)), current_prolog_flag(occurs_check, F).
X = 1,
F = false ;
X = 2,
F = false.
Update after reading comments so that occurs_check continue to be true upon backtracking:
with_occurs_check(G) :-
current_prolog_flag(occurs_check, F),
setup_call_cleanup(
set_prolog_flag(occurs_check, true),
(G, with_occurs_check1(F)),
set_prolog_flag(occurs_check, F)).
with_occurs_check1(F):-
set_prolog_flag(occurs_check, F).
with_occurs_check1(_):-
set_prolog_flag(occurs_check, true),
fail.
Sample run:
?- with_occurs_check((X=1;current_prolog_flag(occurs_check, F), X=2)), current_prolog_flag(occurs_check, F2).
X = 1,
F2 = false ;
X = 2,
F = true,
F2 = false ;
false.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…