开发者

Prolog: Sentence Parser

开发者 https://www.devze.com 2022-12-28 19:57 出处:网络
Been sat here for hours now just staring at this code and have no idea what I\'m doing wrong. I know what\'s happening from tracing the code through (it is going on an eternal loop when it hits verbPh

Been sat here for hours now just staring at this code and have no idea what I'm doing wrong. I know what's happening from tracing the code through (it is going on an eternal loop when it hits verbPhrase). Any tips are more then welcome. Thank you.

% Knowledge-base
det(the).
det(a).

adjective(quick).
adjective(brown).
adjective(orange).
adjective(sweet).

noun(cat).
noun(mat).
noun(fox).
noun(cucumber).
noun(saw).
noun(mother).
noun(father).
noun(family).
noun(depression).

prep(on).
prep(with).

verb(sat).
verb(nibbled).
verb(ran).
verb(looked).
verb(is).
verb(has).

% Sentece Structures
sentence(Phrase) :-
       append(NounPhrase, VerbPhrase, Phrase),
       nounPhrase(NounPhrase),
       verbPhrase(VerbPhrase).

sentence(Phrase) :-
 verbPhrase(Phrase).

nounPhrase([]).

nounPhrase([Head | Tail]) :-
 det(Head),
 nounPhrase2(Tail).

nounPhrase(Phrase) :-
 nounPhrase2(Phrase).

nounPhrase(Phrase) :-
 append(NP, PP, Phrase),
 nounPhrase(NP),
 prepPhrase(PP).

nounPhrase2([]).

nounPhrase2(Word) :-
 noun(Word).

nounPhrase2([Head | Tail]) :-
 adjective(Head),
 nounPhrase2(Tail).

prepPhrase([]).

prepPhrase([Head | Tail]) :-
 prep(Head),
 nounPhrase(Tail).

verbPhrase([]).

verbPhrase(Word) :-
 verb(Word).

verbPhrase([Head | Tail]) :-
 verb(Head),
 nounPhrase(Tail).

verbPhrase(P开发者_如何学Gohrase) :-
 append(VP, PP, Phrase),
 verbPhrase(VP),
 prepPhrase(PP).


I figured it out now after a bit of trolling the internet, so will answer it here if anyone else struggles with it.

The problem was that the append was creating an empty list. This list was passed as a parameter, then split again into two empty lists. And this was repeated over and over again. To stop this, everytime the append function is used, there must be a check if the lists are empty.

For example

verbPhrase(Phrase):-
append(VP, PP, Phrase),
VP \= [],
PP \= [],
verbPhrase(VP),
prepPhrase(PP).
0

精彩评论

暂无评论...
验证码 换一张
取 消