In addition to @Mog's answer, let us consider the more general case:
What, if the grammar is so complex, that reordering DCG-rules will not help? How can we still enumerate all sentences? If the grammar is formulated in such a manner, that it terminates for a fixed length, we get all sentences with
?- length(Xs, N), phrase(s, Xs).
The goal length
alone will enumerate all lists in a fair manner. That is, starting with the shortest []
all lists are enumerated:
?- length(Xs, N).
Xs = [], N = 0
; Xs = [_A], N = 1
; Xs = [_A,_B], N = 2
; Xs = [_A,_B,_C], N = 3
; Xs = [_A,_B,_C,_D], N = 4
; ... .
And now, the length being fixed, the goal phrase(s, Xs)
will find all answers for that fixed length. As an example, look at Mat's answer to this grammar.
So this is a general method to inspect a grammar's sentences. However - there is a price to pay for this generality! For grammars with finitely many sentences, out method will not terminate:
:- use_module(
library(double_quotes)
).
s --> "a"|"b".
?- phrase(s, Xs).
Xs = "a"
; Xs = "b".
This grammar works out of the box, but together with length/2
we get now:
?- length(Xs, N),phrase(s, Xs).
Xs = "a", N = 1
; Xs = "b", N = 1
; loops.
This method is often called iterative deepening, although this term more precisely imposes a bound to the depth of the derivation. But we are imposing a bound to the actual "output". So iterative deepening is also able to handle left-recursion, whereas length/2
works only for grammars that terminate for a fixed input length.
What makes this technique so particularly interesting in Prolog is that it meshes perfectly with Prolog's chronological backtracking mechanism.