Search code examples
prologgrammarcontext-free-grammardcg

How to write a square bracket in prolog?


This may sound strange, but it is used in a parser, I want to be able to parse something of the form

foo[bar]

So this would be represented in a list as:

[foo, [, bar, [] Maybe such a word would be written in DCG as:

x --> id [[] arg []]

The problem is that the square bracket is a reserved character, so how can I represent this in prolog?


Solution

  • Can you not treat your square brackets as atoms (i.e., '[' and ']'), along with everything else?

    How about, for example:

    label1(T) --> id(X), label2(Y), {T =.. [X, Y]}.
    label2(Y) --> ['['], innerexp(Y), [']'].
    id(X) --> [X].
    innerexp(Y) --> [Y].
    

    Execution:

    ?- phrase(label1(T), [foo, '[', bar, ']'], Rem).
    T = foo(bar),
    Rem = [].