开发者

Prolog Question - Simple Grammar Implementation

开发者 https://www.devze.com 2023-03-05 19:03 出处:网络
If I have the following grammar: S → ε S → a S b S How do I implement it in Prolog? I tried this: isMatched([]).

If I have the following grammar:

S → ε

S → a S b S

How do I implement it in Prolog?

I tried this:

isMatched([]).

isMatched([a,b]).

isMatched([a|[S1|[b|S2]]]) :- isMatched(S1), isMatched(S2).

But it obviously doesn't work because the head of a list cannot be a list.

I then tried implementing a new version as follows:

conc([], R, R).

conc([H|T], L, [H|R]) :- conc(T, L, R).

isMatched([]).

isMatched([a,b]).

isMatched(List) :- conc([a], S1, List3), isMatched(S1), conc(List3, [b], List2), conc(List2, S2, List), isMatched(S2).

But for the input isMatched([a,b,a]), it run开发者_开发问答s out of stack.

How do I fix this?


Sounds like homework, so I won't try and do it for you.

You might want to take a look at definite clause grammars (DCGs) in Prolog. This is basically syntactic sugar that allows you to write grammars that read more like grammars than Prolog predicates. If you understand how these work, then you'll probably have a decent understanding of how to parse in Prolog.

0

精彩评论

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