1:- use_module(library(clpfd), [transpose/2]).    2
    3:- meta_predicate guardedmap(:, :, +).    4
    5% TODO goal expansion
    6
    7guardedmap(Guard, Goal, Terms) :-
    8    rb_empty(Seen),
    9    guardedmap_(Guard, Goal, Seen, Terms).
   10
   11guardedmap_(Guard, Goal, Seen, Terms) :-
   12    apply(Guard, Terms)              ->  apply(Goal, Terms) ;
   13    first_visit(Terms, Seen, Seen1)  ->  mapargs(guardedmap_(Guard, Goal, Seen1), Terms) ;
   14    true.
   15
   16
   17%%% UTILS %%%
   18
   19first_visit(Term, Seen0, Seen) :-
   20    rb_insert_new(Seen0, Term, 1, Seen).
   21
   22mapargs(Goal, Terms) :-
   23    maplist(name_arity_args_term(_,_), As0, Terms),
   24    transpose(As0, As),
   25    maplist(Goal, As).
   26
   27name_arity_args_term(Name, Arity, Args, Term) :-
   28    functor(Term, Name, Arity),
   29    Term =.. [_|Args]