Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

prolog - Predicate that, if we input 6 as argument, generates A = 6, B = 0... A = 4, B = 2... A = 2, B = 4... A = 0, B = 6 and ends

This is what I have:

values(Count, A, B) :- 
    A is Count, 
    B is 0. 
values(Count, A, B) :- 
    values(Count, Aa, Bb), 
    A is Aa-2, 
    B is Bb+2,
    + A < 0; 
    B < 0.

So I want by output to be:

A = 6,
B = 0

A = 4,
B = 2

A = 2,
B = 4

A = 0,
B = 6

I'm getting that, but then the interpreter just keeps going and runs out of Stack space, because the recursive values(Count, Aa, Bb) is at the start. I don't know how to rewrite this so that the recursion isn't endless, I want it to end after I get the above output. Would anyone be able to help?


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

1 Reply

0 votes
by (71.8m points)

I would do it like this:

val(A,A,0):- 
    A>=0.
val(C,A,B):-
    CC is C-2,
    CC >=0,
    val(CC,A,BB),
    B is BB+2.

The output is

?- val(6, A, B).
A = 6,
B = 0 ;
A = 4,
B = 2 ;
A = 2,
B = 4 ;
A = 0,
B = 6 ;
false.

So what is the difference? I use the Count variable as counter. It has to decrease in every step to force the recursion to end. The downside is I have to make sure the counter is never less than zero.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...