1/* Part of Extended Libraries for SWI-Prolog 2 3 Author: Edison Mera Menendez 4 E-mail: efmera@gmail.com 5 WWW: https://github.com/edisonm/refactor, http://www.swi-prolog.org 6 Copyright (C): 2013, Process Design Center, Breda, The Netherlands. 7 8 This program is free software; you can redistribute it and/or 9 modify it under the terms of the GNU General Public License 10 as published by the Free Software Foundation; either version 2 11 of the License, or (at your option) any later version. 12 13 This program is distributed in the hope that it will be useful, 14 but WITHOUT ANY WARRANTY; without even the implied warranty of 15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 GNU General Public License for more details. 17 18 You should have received a copy of the GNU General Public 19 License along with this library; if not, write to the Free Software 20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 21 22 As a special exception, if you link this library with other files, 23 compiled with a Free Software compiler, to produce an executable, this 24 library does not by itself cause the resulting executable to be covered 25 by the GNU General Public License. This exception does not however 26 invalidate any other reasons why the executable file might be covered by 27 the GNU General Public License. 28*/ 29 30:- module(substitute, 31 [substitute/3, 32 substitute_value/4, 33 substitute_values/3, 34 is_subterm/2]). 35 36:- meta_predicate substitute( , , ). 37substitute(Comp, Term0, Term) :- 38 ( call(Comp, Term0, Subs) 39 ->Term = Subs 40 ; compound(Term0), 41 functor(Term0, F, A), 42 functor(Term, F, A), 43 substitute(1, Comp, Term0, Term),

45 Term0 \== Term 46 ->true 47 ; Term = Term0 48 )

48. 49 50substitute(N, Comp, Term0, Term) :- 51 arg(N, Term0, Arg0), 52 !, 53 substitute(Comp, Arg0, Arg), 54 arg(N, Term, Arg), 55 succ(N, N1), 56 substitute(N1, Comp, Term0, Term). 57substitute(_, _, _, _). 58 59substitute_one(Value, Var, Term, Var) :- 60 Value==Term. 61 62substitute_value(Value, Subs, Term0, Term) :- 63 substitute(substitute_one(Value, Subs), Term0, Term). 64 65unpair_eq(V=S, V, S). 66 67substitute_values(Pairs, Term0, Term) :- 68 maplist(unpair_eq, Pairs, Values, Subss), 69 foldl(substitute_value, Values, Subss, Term0, Term). 70 71is_subterm(SubTerm, Term) :- 72 substitute_value(SubTerm, Var, Term, Term1), 73 occurrences_of_var(Var, Term1, N), 74 !, 75 N > 0