我試圖解決一個問題,其中給定 M 和 N 整數,以降序回傳一個 M 的冪小于或等于 N 的串列。例如:powers(3,9,res)。水庫= [9,3,1]
我的方法如下:
power(X,0,1).
power(X,Y,Z) :- X>0,
Yminus1 is Y - 1,
power(X,Yminus1,Z1),
Z is X*Z1.
increment(X,newX) :- newX is X 1.
powers(M,N,res) :- integer(M), integer(N),
powersAux(M,N,0,res).
powersAux(M,N,E,res) :- power(M,E,Z),
Z=<N,
increment(E,E1),
res1 = [Z|res],
powersAux(M,N,E1,res1).
我正在填滿我的記憶體堆疊,所以我知道遞回永遠不會結束。
uj5u.com熱心網友回復:
您需要處理特殊情況:
- 0 n始終為 0
- 1 n總是 1
Prolog 有一個內置的求冪函式:**/2.
一個常見的 Prolog 習慣用法是有一個在約束驗證之外幾乎不做任何事情的公共謂詞,它呼叫一個“內部”輔助謂詞來完成作業。輔助謂詞通常采用額外的引數來維護計算所需的狀態。
這導致了這一點:
powers( X , L, Ps ) :-
non_negative_integer(X),
non_negative_integer(L),
powers(X,0,L,[],Ps)
.
non_negative_integer(X) :- integer(X), X >= 0 .
% ---------------------------------------------------------------
%
% powers( Base, Exponent, Limit, Accumulator, ?Results )
%
% where Base and Radix are guaranteed to be non-negative integers
% ---------------------------------------------------------------
powers( 0 , _ , _ , _ , [0] ) :- ! . % 0^n is always 0
powers( 1 , _ , 0 , _ , [] ) :- ! . % 1^n is always 1
powers( 1 , _ , L , _ , [1] ) :- L >= 1 , !. % 1^n is always 1
powers( X , Y , L , Ps , Ps ) :- X**Y > L , !. % when x^y exceeds the limit, we're done, and
powers( X , Y , L , Ts , Ps ) :- % otherrwise...
T is X**Y , % - compute T as x^y
Y1 is Y 1, % - increment Y
powers(X,Y1,L,[T|Ts],Ps) % - recurse down, prepending T to the accumulator list.
. % Easy!
這給了我們
?- powers(2,1024,Ps).
Ps = [1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/486358.html
上一篇:為什么這個遞回python代碼列印y而不能回傳y?[復制]
下一篇:從深度未知的嵌套陣列中洗掉專案
