I have two lists:
grammarNonterminal = {{VP,{V,NP}},{NP,{D,N}},{S,{NP,VP}}} sentence = {{D,"the"},{N,"man"},{V,"hit"},{D,"the"},{N,"table"}} I want to make a function which changes sentence into the followings when the function takes grammarNonterminal and sentence as arguments.
⇒ {{NP, {D, "the"}, {N,"man"}}, {V, "hit"}, {D, "the"}, {N, "table"}}} , {{{D, "the"}, {N, "man"}, {V, "hit"}, {NP, {{D, "the"}, {N, “table"}}}, ⇒ {{NP, {D, "the"}, {N, "man"}}, {V, "hit"}, {NP, {D, "the"}, {N, "table"}}}},{{D, "the"}, {N, "man"}, {VP, {{V, "hit"}, {NP, {D, "the"}, {N, "table"}}} ⇒ {{{NP, {D, "the"}, {N, "man"}}, {VP, {{V, "hit"}, {NP, {{D, "the"}, {N, "table"}}}}} ⇒ {{{S, {NP, {D, "the"}, {N, "man"}}, {VP, {{V, "hit"}, {NP, {{D, "the"}, {N, "table"}}}}}} I know I have to use ReplaceList, Map and Union to achieve this.
Is there a simple way to do this?
What I wanted to do is something like below.
First, you make a function applyRule:
applyRule[sentence_, r_] := ReplaceList[sentence,{x___,c : Apply[PatternSequence, {#, _} & /@ r[[2]] ], y___} -> {x, ReplacePart[r, 2 -> {c}], y}]; r = {NP,{D,N}} applyRule[sentence,r] = {{{NP, {{D, "the"}, {N, "man"}}}, {V, "hit"}, {D, "the"}, {N, "table"}}, {{D,"the"}, {N, "man"}, {V, "hit"}, {NP, {{D, "the"}, {N, "table"}}}}} And then make a function to change sentence into
{{{S, {NP, {D, "the"}, {N, "man"}}, {VP, {{V, "hit"}, {NP, {{D, "the"}, {N, "table"}}}}}} by using applyRule, Map, and Union.
I tried
Union[Map[applyRule[sentence, #] &, grammarNonterminal] but this doesn't give me the result that I want.


D, word, N, wordget replaced first, then only later the other one? How do we specify the order in which terms get replaced? Must it happen from the end of the sentence backward? Probably not, because eventually, theD, word, N, wordat the beginning of the sentence gets replaced, but that's only after nothing else can be replaced. Anyway, more info please! $\endgroup$DandNhave built-in Mathematica meanings. I recommend usingvp,np,d,v, andn. $\endgroup${{{S, {NP, {D, "the"}, {N, "man"}}, {VP, {{V, "hit"}, {NP, {{D, "the"}, {N, "table"}}}}}}in the end. I just edited the question to add some explanations. $\endgroup$