Prolog: pattern matching within a list

一世执手 提交于 2019-12-11 13:37:06

问题


Define a relation xyz(X) that is true if X is a xyz sequence. A xyz sequence is a sequence that consists of either the number 0, or the number 1 followed by two other xyz sequences.

Some xyz sequences:

xyz([0]).
xyz([1,0,1,0,0]).

And, the following are not considered xyz sequences:

xyz([1,1,0,0]).
xyz([0,1,0]).
xyz([1,1,0]).
xyz([1,0,1,1,1,1,1,0,1]).

Can someone help me with how to approach this problem?


回答1:


The easiest is to write a DCG. See this tutorial for a thorough introduction. You can literally write down the problem statement verbatim to get a solution:

xyz --> [0].
xyz --> [1], xyz, xyz.

You will need phrase:

?- phrase(xyz, [1,0,1,0,0]).

This solution leaves behind a choice point.




回答2:


such simple grammar is ideal to understand the mechanism (albeit simplified) that powers DCGs:

seq(S) :- seq(S, []).

seq([0|R], R).
seq([1|T], R) :- seq(T, Q), seq(Q, R).


来源:https://stackoverflow.com/questions/28893265/prolog-pattern-matching-within-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!