% This LaTeX document was generated using the LaTeX backend of PlDoc, % The SWI-Prolog documentation system \section{library(occurs): Finding and counting sub-terms} \label{sec:occurs} \begin{tags} \tag{See also} \file{library(terms)} provides similar predicates and is probably more wide-spread than this library. \end{tags} This is a SWI-Prolog implementation of the corresponding Quintus library, based on the generalised \predref{arg}{3} predicate of SWI-Prolog.\vspace{0.7cm} \begin{description} \predicate[semidet]{contains_term}{2}{+Sub, +Term} Succeeds if \arg{Sub} is contained in \arg{Term} (=, deterministically) \predicate[semidet]{contains_var}{2}{+Sub, +Term} Succeeds if \arg{Sub} is contained in \arg{Term} (==, deterministically) \predicate[semidet]{free_of_term}{2}{+Sub, +Term} Succeeds of \arg{Sub} does not unify to any subterm of \arg{Term} \predicate[semidet]{free_of_var}{2}{+Sub, +Term} Succeeds of \arg{Sub} is not equal (\Sequal{}) to any subterm of \arg{Term} \predicate[det]{occurrences_of_term}{3}{@SubTerm, @Term, ?Count} \arg{Count} the number of SubTerms in \arg{Term} that \textit{unify} with \arg{SubTerm}. As this predicate is implemented using backtracking, \arg{SubTerm} and \arg{Term} are not further instantiated. Possible constraints are enforced. For example, we can count the integers in \arg{Term} using \begin{code} ?- freeze(S, integer(S)), occurrences_of_term(S, f(1,2,a), C). C = 2, freeze(S, integer(S)). \end{code} \begin{tags} \tag{See also} \predref{occurrences_of_var}{3} for an equality (\predref{\Sequal}{2}) based variant. \end{tags} \predicate[det]{occurrences_of_var}{3}{@SubTerm, @Term, ?Count} \arg{Count} the number of SubTerms in \arg{Term} that are \textit{equal} to \arg{SubTerm}. Equality is tested using \predref{\Sequal}{2}. Can be used to count the occurrences of a particular variable in \arg{Term}. \begin{tags} \tag{See also} \predref{occurrences_of_term}{3} for a unification (\predref{\Seq}{2}) based variant. \end{tags} \predicate{sub_term}{2}{-Sub, +Term} Generates (on backtracking) all subterms of \arg{Term}. \predicate{sub_var}{2}{-Sub, +Term} Generates (on backtracking) all subterms (\Sequal{}) of \arg{Term}. \predicate[det]{sub_term_shared_variables}{3}{+Sub, +Term, -Vars} If \arg{Sub} is a sub term of \arg{Term}, \arg{Vars} is bound to the list of variables in \arg{Sub} that also appear outside \arg{Sub} in \arg{Term}. Note that if \arg{Sub} appears twice in \arg{Term}, its variables are all considered shared. An example use-case is refactoring a large clause body by introducing intermediate predicates. This predicate can be used to find the arguments that must be passed to the new predicate. \end{description}