# Writing a CSG in DCG notation

**URL:** <https://swi-prolog.discourse.group/t/writing-a-csg-in-dcg-notation/9857>\
**Category:** General\
**Created:** [October 8, 2026, 3:23pm UTC](https://swi-prolog.discourse.group/t/writing-a-csg-in-dcg-notation/9857 "2026-10-08T15:23:08Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![stassa.p](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/stassa.p/32/712_2.png) [@stassa.p](https://swi-prolog.discourse.group/u/stassa.p)\
**Post date:** [October 8, 2026, 3:23pm UTC](https://swi-prolog.discourse.group/t/writing-a-csg-in-dcg-notation/9857/1 "2026-10-08T15:23:08Z")

</div>

I am trying to find a way to write the classic a^nb^nc^n Context Sensitive Grammar (CSG) from Hopcroft & Ullman in DCG notation. The book gives the productions of the grammar as follows:

1. S \rightarrow aSBC
2. S \rightarrow aBC
3. CB \rightarrow BC
4. aB \rightarrow ab
5. bB \rightarrow bb
6. bC \rightarrow bc
7. cC \rightarrow cc

First, note that I’m not simply interested in DCG or a Prolog program that can generate strings of a’s, b’s and c’s of the same length one after the other: I know how to do that. What I’m trying to understand is how I can represent a CSG in DCG notation.

More specifically, I guess I’m trying to understand what is the best way to denote that the left-hand side of a DCG production has a “context”. Recall that a CSG has productions of the form \alpha A\beta \rightarrow \alpha\gamma\beta where A is a non-terminal symbol and \alpha, \beta, \gamma are a mix of terminals and non-terminals. In the left-hand side of a production \alpha A\beta \rightarrow \alpha\gamma\beta, the \alpha and \beta form the “context” of the rule so that A is replaced by the string \gamma if and only if it is surrounded by \alpha and \beta in an input string.

The practical difficulty is that it’s not clear how to represent a rule that has _only_ non-terminals on the left-hand side, like production 3 in the a^nb^nc^n listing above:

1. CB \rightarrow BC

The problem is that the grammar must process a string of both terminals and non-terminals but when we parse a string with a DCG, the grammar only consumes terminals from its input.

To make up for that I tried the following:

```prolog
s([a,'S','B','C'|Ss]) --> ['S'], s(Ss).
s([a,'B','C'|Ss]) --> ['S'], s(Ss).
s(['B','C'|Ss]) --> ['C','B'], s(Ss).
s([a,b|Ss]) --> [a,'B'], s(Ss).
s([b,b|Ss]) --> [b,'B'], s(Ss).
s([b,c|Ss]) --> [b,'C'], s(Ss).
s([c,c|Ss]) --> [c,'C'], s(Ss).

s(['B'|Ss]) --> ['B'], s(Ss).
s(['C'|Ss]) --> ['C'], s(Ss).
s([a|Ss]) --> [a], s(Ss).
s([b|Ss]) --> [b], s(Ss).
s([c|Ss]) --> [c], s(Ss).
s([]) --> [].

```

That is to say, I tried to generate a string of terminals and non-terminals that is progressively whittled down to terminals during parsing and placed in the “output” of the grammar.

This requires a dedicated interpreter, which I defined as follows:

```prolog
csg(_S,Os,0,Os):-
        !.
csg(S,Is,N,Os):-
        S_ =.. [S,Ss]
        ,phrase(S_, Is)
        ,N_ is N - 1
        ,csg(S,Ss,N_,Os).

```

This is based on some earlier work on L-Systems I won’t bore you with, but that’s where the counting-down comes from (L-systems have a concept of “generation” that requires counting).

This setup allows me to generate strings like the following:

```prolog
248 ?- csg(s,['S'],3,Ps).
Ps = [a, a, a, 'S', 'B', 'C', 'B', 'B', 'C', 'C'] ;
Ps = [a, a, a, 'S', 'B', 'C', 'B', 'C', 'B', 'C'] ;
Ps = [a, a, a, 'B', 'C', 'B', 'B', 'C', 'C'] ;
Ps = [a, a, a, 'B', 'C', 'B', 'C', 'B', 'C'] ;
Ps = [a, a, b, 'B', 'C', 'C'] ;
Ps = [a, a, b, 'C', 'B', 'C'] ;
Ps = [a, a, 'B', 'B', 'C', 'C'] ;
Ps = [a, a, 'B', 'C', 'B', 'C'] ;
Ps = [a, b, c] ;
Ps = [a, b, 'C'] ;
Ps = [a, b, 'C'] ;
Ps = [a, 'B', 'C'] ;

```

Where [a,b,c] is the target. The others are really partial parses on the way to [a,b,c]. It’s possible to filter the output to keep only the strings composed exclusively of terminals, or just keep parsing until only terminals are left, but I don’t think this is really on the right track.

Note that if I try to restrict the output of csg/4 to a certain length that blows up the stacks, as expected (CSG parsing is in PSPACE). So if you try `?- csg(s,['S'],3,[A,B,C]).` that dies a death, as does `?- csg(s,['S'],3,[a,b,c]).`.

So my question to the community is: does anyone know a better way to do this?

Is there a better way to define Hopcroft & Ullman’s a^nb^nc^n CSG as a DCG? Btw that CSG is Example 2.2 on page 13 of my copy of _Formal Languages and their Relation to Automata_.

What is the best way to represent CSGs with rules like production 3 above in DCG notation?

Thanks in advance.

---

<div class="post-metadata">

**Author:** ![stassa.p](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/stassa.p/32/712_2.png) [@stassa.p](https://swi-prolog.discourse.group/u/stassa.p)\
**Post date:** [October 8, 2026, 3:50pm UTC](https://swi-prolog.discourse.group/t/writing-a-csg-in-dcg-notation/9857/2 "2026-10-08T15:50:25Z")

</div>

As an update, here’s a version of the above grammar and interpreter that returns only strings of terminals and doesn’t blow up the stacks (thanks to our old friend the cut !/0):

```prolog
ground_csg(_S,Os,0,Os):-
        forall(member(A,Os)
              ,(atom_codes(A,[C])
               ,between(0'a,0'z,C)
               )
              )
        ,!.
ground_csg(S,Is,N,Os):-
        S_ =.. [S,Ss]
        ,phrase(S_,Is)
        ,N_ is N - 1
        ,N_ >= 0
        ,ground_csg(S,Ss,N_,Os).

s([a,'S','B','C'|Ss]) --> ['S'], s(Ss).
s([a,'B','C'|Ss]) --> ['S'], s(Ss).
s(['B','C'|Ss]) --> ['C','B'], !, s(Ss).
s([a,b|Ss]) --> [a,'B'], !, s(Ss).
s([b,b|Ss]) --> [b,'B'], !, s(Ss).
s([b,c|Ss]) --> [b,'C'], !, s(Ss).
s([c,c|Ss]) --> [c,'C'], !, s(Ss).

s(['B'|Ss]) --> ['B'], !, s(Ss).
s(['C'|Ss]) --> ['C'], !, s(Ss).
s([a|Ss]) --> [a], !, s(Ss).
s([b|Ss]) --> [b], !, s(Ss).
s([c|Ss]) --> [c], !, s(Ss).
s([]) --> [].

```

So now we can do:

```prolog
[debug] 298 ?- ground_csg(s,['S'],3,Ps), !.
Ps = [a, b, c].

[debug] 299 ?- ground_csg(s,['S'],6,Ps), !.
Ps = [a, a, b, b, c, c].

[debug] 300 ?- ground_csg(s,['S'],9,Ps), !.
Ps = [a, a, a, b, b, b, c, c, c].

```

And even:

```prolog
[debug] 303 ?- time( ground_csg(s,['S'],9,[a,b,c]) ), !.
% 2,105 inferences, 0.000 CPU in 0.000 seconds (0% CPU, Infinite Lips)
true.

[debug] 304 ?- time( ground_csg(s,['S'],9,[a,a,b,b,c,c]) ), !.
% 1,944 inferences, 0.000 CPU in 0.000 seconds (0% CPU, Infinite Lips)
true.

[debug] 305 ?- time( ground_csg(s,['S'],9,[a,a,a,b,b,b,c,c,c]) ), !.
% 1,798 inferences, 0.000 CPU in 0.000 seconds (0% CPU, Infinite Lips)
true.

[debug] 306 ?- time( ground_csg(s,['S'],9,[a,a,a,a,b,b,b,b,c,c,c,c]) ), !.
% 2,263 inferences, 0.000 CPU in 0.000 seconds (0% CPU, Infinite Lips)
false.

```

But still, I don’t think this is right. There must be a better way to do it so that all those intermediary parses are not output?

---

<div class="post-metadata">

**Author:** ![brebs](https://avatars.discourse-cdn.com/v4/letter/b/e9c0ed/32.png) [@brebs](https://swi-prolog.discourse.group/u/brebs)\
**Post date:** [October 8, 2026, 9:40pm UTC](https://swi-prolog.discourse.group/t/writing-a-csg-in-dcg-notation/9857/3 "2026-10-08T21:40:14Z")

</div>

> [@stassa.p](#):
>
> ```prolog
> csg(_S,Os,0,Os):-
> !.
> 
> ```

Just curious - shouldn’t this be:

```prolog
csg(_S, Os, 0, Result) :-
    !,
    Result = Os.

```

… to count down to zero robustly even if Result is nonvar.

---

<div class="post-metadata">

**Author:** ![stassa.p](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/stassa.p/32/712_2.png) [@stassa.p](https://swi-prolog.discourse.group/u/stassa.p)\
**Post date:** [October 9, 2026, 9:14am UTC](https://swi-prolog.discourse.group/t/writing-a-csg-in-dcg-notation/9857/4 "2026-10-09T09:14:34Z")

</div>

Sure, why not? Although this is just for my personal use so there’s no need for much safety.

---

<div class="post-metadata">

**Author:** ![brebs](https://avatars.discourse-cdn.com/v4/letter/b/e9c0ed/32.png) [@brebs](https://swi-prolog.discourse.group/u/brebs)\
**Post date:** [October 9, 2026, 9:34am UTC](https://swi-prolog.discourse.group/t/writing-a-csg-in-dcg-notation/9857/5 "2026-10-09T09:34:57Z")

</div>

> [@stassa.p](#):
>
> there’s no need for much safety

If the program can count down to infinity rather than stopping at zero like it’s supposed to, that’s a bug 😉

---

<div class="post-metadata">

**Author:** ![stassa.p](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/stassa.p/32/712_2.png) [@stassa.p](https://swi-prolog.discourse.group/u/stassa.p)\
**Post date:** [October 9, 2026, 10:01am UTC](https://swi-prolog.discourse.group/t/writing-a-csg-in-dcg-notation/9857/6 "2026-10-09T10:01:46Z")

</div>

Sorry for my earlier answer, it was too snarky, in retrospect.

To be frank, I think that “steadfastness” you recommend is too much fuss for the use case. I’m the only one who’s going to use that piece of code. I’ll only call it at the top-level most likely. If I manage to bind the last argument and it goes infinite, I’ll just kill the session and start anew. There is no significant risk of any sort.

To be more frank I don’t like to pepper my Prolog code with safety clauses. I think it’s too fussy, it distracts my eyes when I scan code quickly and it reminds me of the code I used to write when I was working in a Java shop that was literally 80% exception handling. Awful stuff.

I like my Prolog fast and dangerous. I am not even sure if I understand correctly what “steadfastness” means.
