% This LaTeX document was generated using the LaTeX backend of PlDoc, % The SWI-Prolog documentation system \section{library(dcg/high_order): High order grammar operations} \label{sec:highorder} This library provides facilities comparable \predref{maplist}{3}, \predref{ignore}{1} and \predref{foreach}{2} for DCGs. \textbf{STATUS}: This library is experimental. The interface and implementation may change based on feedback. Please send feedback to the mailinglist or the issue page of the \verb$swipl-devel.git$ repository.\vspace{0.7cm} \begin{description} \dcg[nondet]{sequence}{2}{:Element, ?List} Match or generate a sequence of \arg{Element}. This predicate is deterministic if \arg{List} is fully instantiated and \arg{Element} is deterministic. When parsing, this predicate is \textit{gready} and does not prune choice points. For example: \begin{code} ?- phrase(sequence(digit, Digits), `123a`, L). Digits = "123", L = [97] ; Digits = [49, 50], L = [51, 97] ; ... \end{code} \dcg[nondet]{sequence}{3}{:Element, :Sep, ?List} Match or generate a sequence of \arg{Element} where each pair of elements is separated by \arg{Sep}. When \textit{parsing}, a matched \arg{Sep} \textit{commits}. The final element is \textit{not} committed. More formally, it matches the following sequence: \begin{code} Element?, (Sep,Element)* \end{code} See also \dcgref{sequence}{5}. \dcg[semidet]{sequence}{5}{:Start, :Element, :Sep, :End, ?List} Match or generate a sequence of \arg{Element} enclosed by \arg{Start} end \arg{End}, where each pair of elements is separated by \arg{Sep}. More formally, it matches the following sequence: \begin{code} Start, Element?, (Sep,Element)*, End \end{code} The example below matches a Prolog list of integers: \begin{code} ?- phrase(sequence(("[",blanks), number, (",",blanks), (blanks,"]"), L), `[1, 2, 3 ] a`, Tail). L = [1, 2, 3], Tail = [32, 97]. \end{code} \dcg[det]{optional}{2}{:Match, :Default} Perform an optional match, executing \arg{Default} if \arg{Match} is not matched. This is comparable to \predref{ignore}{1}. Both \arg{Match} and \arg{Default} are DCG body terms. \arg{Default} is typically used to instantiate the output variables of \arg{Match}, but may also be used to match a default representation. Using \verb$[]$ for \arg{Default} succeeds without any additional actions if \arg{Match} fails. For example: \begin{code} ?- phrase(optional(number(X), {X=0}), `23`, Tail). X = 23, Tail = []. ?- phrase(optional(number(X), {X=0}), `aap`, Tail). X = 0, Tail = `aap`. \end{code} \dcg[det]{foreach}{2}{:Generator, :Element} \nodescription \dcg[det]{foreach}{3}{:Generator, :Element, :Sep} Generate a list from the solutions of \arg{Generator}. This predicate collects all solutions of \arg{Generator}, applies \arg{Element} for each solution and \arg{Sep} \textit{between} each pair of solutions. For example: \begin{code} ?- phrase(foreach(between(1,5,X), number(X), ", "), L). L = "1, 2, 3, 4, 5". \end{code} \end{description}