Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

How to generate the language of all binary strings of length n-1 using a DCG in Prolog

z(1) --> [].
z(N) --> [0] , z(Nm), {N is Nm+1}.
z(N) --> [1] , z(Nm), {N is Nm+1}. 

This is what I have so far. I want to generate

[0,0]
[0,1]
[1,0]
[1,1]

but instead runs into an infinite loop after [0, 0]

when you query

?- z(3, X, []).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

If you will always call the predicate with N as integer, you can try:

z(1) --> [].
z(N) --> [0] , {N>1, Nm is N-1}, z(Nm).
z(N) --> [1] , {N>1, Nm is N-1}, z(Nm).

Result:

?- z(3, X, []).
X = [0, 0] ;
X = [0, 1] ;
X = [1, 0] ;
X = [1, 1] ;
false.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...