Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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, []).

1 Answers

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.
like image 56
slago Avatar answered Nov 22 '25 12:11

slago



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!