since the grammar is not left recursive, we can use DCG :
s
then we can parse or generate all the accepted sequences. For example, generating:
?- length(L, _), phrase(s, L). L = [o] L = [m, o, n] L = [m, m, o, n, n] ...
To check the Prolog code:
?- listing(s). s(A, B) :- a(A, B). ?- listing(a). a([m|A], C) :- a(A, B), B=[n|C]. a([o|A], A).
no need to add / 3 thanks to difference lists
edit using append / 3
s(Z) :- a(Z). a(Z) :- append([m|X],[n],Z), a(X). a([o]).
SWI-Prolog has append / 2 (just based on append / 3 properly docked) that provide a more readable alternative
a(Z) :- append([[m],X,[n]], Z), a(X).
in any case, we must call recursively / 1 after the list has been built / split