Search code examples
prologdcg

Prolog grammar productions


I am trying to learn how to write production rules in prolog. This is what I have.

paragraph --> sentence, paragraph ; [].
sentence --> proper_noun, [ ], verb, [ ], preposition, [ ], article, [ ], noun, period.
proper_noun --> [Jimmy] ; [Yancy] ; [Clementine] ; [Astrid].
verb --> [runs] ; [walks] ; [skips] ; [flies].
preposition --> [to] ; [at] ; [around] ; [through].
article --> [the]    ; [a].
noun --> [school] ; [house] ; [car] ; [spaceship].
period -->[.].

I tried to call it using

 phrase( sentence, [Jimmy," ",walks," ",to," ",the," ",school], [] ), atom_codes( Output,[Jimmy," ",walks," ",to," ",the," ",school]).

It returned false as an output. Please help me understand where I went wrong and how I can write better grammars.


Solution

  • use 'Jimmy' etc. (i.e. put all atoms starting with capital letters into quotes). Otherwise they are interpreted as logical variables. you do get lots of "Singleton variables" warnings.

    you've also missed some parentheses, and made few more typos:

    paragraph --> sentence, ( paragraph ; []).
    sentence --> proper_noun, verb, preposition, article, noun, period.
    proper_noun --> ['Jimmy'] ; ['Yancy'] ; ['Clementine'] ; ['Astrid'].
    verb --> [runs] ; [walks] ; [skips] ; [flies].
    preposition --> [to] ; [at] ; [around] ; [through].
    article --> [the] ; [a].
    noun --> [school] ; [house] ; [car] ; [spaceship].
    period -->[.].
    

    Testing it:

    30 ?- phrase( sentence, ['Jimmy', walks, to, the, school, .], [] ).
    true ;
    false.