View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2018, VU University Amsterdam
    7                         CWI, Amsterdam
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module(dcg_high_order,
   37          [ sequence//2,                % :Element, ?List
   38            sequence//3,                % :Element, :Sep, ?List
   39            sequence//5,                % :Start, :Element, :Sep, :End, ?List
   40            optional//2,                % :Match, :Otherwise
   41            foreach//2,                 % :Generator, :Element
   42            foreach//3                  % :Generator, :Element, :Sep
   43          ]).   44:- use_module(library(ordsets)).   45
   46:- meta_predicate
   47    sequence(3,?,?,?),
   48    sequence(3,//,?,?,?),
   49    sequence(//,3,//,//,?,?,?),
   50    optional(//, //, ?, ?),
   51    foreach(0,//,?,?),
   52    foreach(0,//,//,?,?).

High order grammar operations

This library provides facilities comparable maplist/3, ignore/1 and foreach/2 for DCGs.

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 swipl-devel.git repository. */

 sequence(:Element, ?List)// is nondet
Match or generate a sequence of Element. This predicate is deterministic if List is fully instantiated and Element is deterministic. When parsing, this predicate is gready and does not prune choice points. For example:
?- phrase(sequence(digit, Digits), `123a`, L).
Digits = "123",
L = [97] ;
Digits = [49, 50],
L = [51, 97] ;
...
   78sequence(OnElem, List) -->
   79    sequence_(List, OnElem).
   80
   81sequence_([H|T], P) -->
   82    call(P, H),
   83    sequence_(T, P).
   84sequence_([], _) -->
   85    [].
 sequence(:Element, :Sep, ?List)// is nondet
Match or generate a sequence of Element where each pair of elements is separated by Sep. When parsing, a matched Sep commits. The final element is not committed. See also sequence//5.
   93sequence(OnElem, OnSep, List) -->
   94    sequence_(List, OnElem, OnSep).
 sequence(:Start, :Element, :Sep, :End, ?List)// is semidet
Match or generate a sequence of Element enclosed by Start end End, where each pair of elements is separated by Sep. More formally, it matches the following sequence:
Start (Element,Sep)*, End

The example below matches a Prolog list of integers:

?- phrase(sequence(("[",blanks),
                   number, (",",blanks),
                   (blanks,"]"), L),
                   `[1, 2, 3 ] a`, Tail).
L = [1, 2, 3],
Tail = [32, 97].
  113sequence(Start, OnElem, OnSep, End, List) -->
  114    Start,
  115    sequence_(List, OnElem, OnSep),
  116    End, !.
  117
  118sequence_([H|T], P, Sep) -->
  119    call(P, H),
  120    (   {T == []}
  121    ->  []
  122    ;   Sep
  123    ->  !, sequence_(T, P, Sep)
  124    ;   {T = []}
  125    ).
  126sequence_([], _, _) -->
  127    [].
 optional(:Match, :Default)// is det
Perform an optional match, executing Default if Match is not matched. This is comparable to ignore/1. Both Match and Default are DCG body terms. Default is typically used to instantiate the output variables of Match, but may also be used to match a default representation. Using [] for Default succeeds without any additional actions if Match fails. For example:
?- phrase(optional(number(X), {X=0}), `23`, Tail).
X = 23,
Tail = [].
?- phrase(optional(number(X), {X=0}), `aap`, Tail).
X = 0,
Tail = `aap`.
  146optional(Match, _Default) -->
  147    Match, !.
  148optional(_, Default) -->
  149    Default, !.
 foreach(:Generator, :Element)// is det
 foreach(:Generator, :Element, :Sep)// is det
Generate a list from the solutions of Generator. This predicate collects all solutions of Generator, applies Element for each solution and Sep between each pair of solutions. For example:
?- phrase(foreach(between(1,5,X), number(X), ", "), L).
L = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10".
  161foreach(Generator, Rule) -->
  162    foreach(Generator, Rule, []).
  163
  164foreach(Generator, Rule, Sep) -->
  165    { term_variables(Generator, GenVars0),   sort(GenVars0, GenVars),
  166      term_variables((Rule,Sep), GoalVars0), sort(GoalVars0, GoalVars),
  167      ord_subtract(GoalVars, GenVars, SharedGoalVars),
  168      ord_intersection(GenVars, GoalVars, SharedVars),
  169      Templ =.. [v|SharedVars],
  170      SharedTempl =.. [v|SharedGoalVars],
  171      findall(Templ, Generator, List)
  172    },
  173    emit_list(List, Templ, SharedTempl, Rule, Sep).
  174
  175emit_list([], _, _, _, _) -->
  176    [].
  177emit_list([H|T], Templ, SharedTempl, OnElem, OnSep) -->
  178    { copy_term(t(Templ,SharedTempl,OnElem,OnSep),
  179                t(H,SharedTempl,OnElemCopy,OnSepCopy))
  180    },
  181    OnElemCopy,
  182    (   { T == [] }
  183    ->  []
  184    ;   OnSepCopy,
  185        emit_list(T, Templ, SharedTempl, OnElem, OnSep)
  186    ).
  187
  188
  189                /*******************************
  190                *            SANDBOX           *
  191                *******************************/
  192
  193:- multifile sandbox:safe_meta_predicate/1.  194
  195sandbox:safe_meta_predicate(dcg_high_order:sequence/4).
  196sandbox:safe_meta_predicate(dcg_high_order:sequence/5).
  197sandbox:safe_meta_predicate(dcg_high_order:sequence/7).
  198sandbox:safe_meta_predicate(dcg_high_order:optional/4).
  199sandbox:safe_meta_predicate(dcg_high_order:foreach/4).
  200sandbox:safe_meta_predicate(dcg_high_order:foreach/5)