开发者

Parsing in prolog

开发者 https://www.devze.com 2023-03-10 16:52 出处:网络
run([H|T]) --> num(H),run(T). run([T]) --> num(T). num(increase) --> [increase],{write(1),nl}.
run([H|T]) --> num(H),run(T).
run([T]) --> num(T).
num(increase) --> [increase],{write(1),nl}.
num(decrease) --> [decrease],{write(0),nl}.

In this parser when increase is given it prints 1, when decrease given i开发者_运维知识库t prints 0. However, there occurs a problem when processing the last element of the list. For instance run(A,[increase],[]) prints two 1's. run(A,[increase,decrease],[]) prints one 1 and two 0's, a thing which i don't want. How can i make it work properly so that run(A,[increase],[]) prints 1 and run(A,[increase,decrease],[]) prints 1,0 ?


Both clauses of run//1 match in this case. Consider changing the second clause of run//1 to:

run([]) --> [].

Independently, consider using phrase/2 (like phrase(run(A), [increase])) for portability, instead of assuming a particular expansion method for DCGs.

0

精彩评论

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