title: Sentence Parser - Prolog
body: <p>I decided to repost, after some formatting complaints on my previous submission.</p>
  
  <p>The program, should parse the list [a,command,moving,to,a,higher,directory] into:</p>
  
  <p>det(a),noun(command),verb(moving),prep(to),det(a),adj(higher),noun(directory).</p>
  
  <p>However the program fails after trying to assign a det(to), when instead it should go through and assign to as a prepositional phrase (prep).</p>
  
  <p>This is definitely a backtracking issue, but can anyone spot whats wrong with my code? </p>
  
  <p>Program:</p>
  
  <pre><code>/* Facts */
  det(the).
  det(a).
  det(more).
  
  prep(in).
  prep(to).
  
  noun(detail).
  noun(command).
  noun(directory).
  noun(file).
  noun('08226txt').
  
  adj(moving).
  adj(parent).
  adj(current).
  adj(fine).
  adj(higher).
  adj(short).
  adj(very).
  
  verb(moves).
  verb(print).
  verb(types).
  verb(viewed).
  verb(listing).
  verb(moving).
  
  
  /* S -&gt; NP VP
     S -&gt; VP */
  sentence(Sentence,sentence(np(Noun_Phrase),vp(Verb_Phrase))):-
    np(Sentence,Noun_Phrase,Rem),
    vp(Rem,Verb_Phrase).
  
  /* NP -&gt; Det NP2
     NP -&gt; NP2
     NP -&gt; NP PP */
  np([X|T],np(det(X),NP2),Rem):-
    det(X),
    np2(T,NP2,Rem).
  np(Sentence,Parse,Rem):- np2(Sentence,Parse,Rem).
  np(Sentence,np(NP,PP),Rem):-
    np(Sentence,NP,Rem1),
    pp(Rem1,PP,Rem).
  
  /* NP2 -&gt; Noun
     NP2 -&gt; Adj NP2 */
  np2([H|T],np2(noun(H)),T):- noun(H).
  np2([H|T],np2(adj(H),Rest),Rem):-
        adj(H),
        np2(T,Rest,Rem).
  
  /* PP -&gt; Prep NP */
  pp([H|T],pp(prep(H),Parse),Rem):-
    prep(H),
    np(T,Parse,Rem).
  
  /* VP -&gt; Verb
     VP -&gt; Verb NP
     VP -&gt; VP PP */
  vp([H|[]],verb(H)):-
    verb(H).
  vp([H|Rest],vp(verb(H),RestParsed)):-
    verb(H),
    np(Rest,RestParsed,_).
  vp([H|Rest],vp(verb(H),RestParsed)):-
    vp(H,Rest),
    pp(Rest,RestParsed,_).
  </code></pre>
  
  <p>Program output with trace:<a href="https://i.stack.imgur.com/mO5A9.png" rel="nofollow noreferrer">Ouput</a></p>
  
  <p>Any help would be greatly appreciated. </p>