Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create this DCG in Prolog?

I want to create a DCG that languages like this get accepted:

  • c
  • bbbcbbb
  • bbacbba
  • abacaba
  • aababacaababa

As you can see this means that there is a specific order of a and b, then one c and then again the exact same order as before the c. If these conditions are not met it shall fail.

I am currently here with my approach (works, but also recognizes wrong words)

s --> x, s, x. 
s --> [c]. 
x --> [a]. 
x --> [b]. 

Can someone of you help me out what I need to change? I don't know how to go on. Thanks a lot.

like image 400
Waylander Avatar asked Feb 11 '14 13:02

Waylander


1 Answers

A DCG is really just a Prolog program, preprocessed adding hidden arguments that implement a difference list. We can always add our own parameters, and use pattern matching. Then

s --> ab(X), [c], ab(X). 
ab([a|T]) --> [a], ab(T).
ab([b|T]) --> [b], ab(T).
ab([]) --> [].

?- atom_chars(aababacaababa,Cs),phrase(s, Cs).
Cs = [a, a, b, a, b, a, c, a, a|...] 
like image 195
CapelliC Avatar answered Oct 13 '22 19:10

CapelliC