作業是取兩個變量,一個介於0和10,000之間的數字以及1和這個數字之間有多少個圓形素數。強迫變量重新分配(Prolog)
我無法通過遞歸傳回變量(回溯是它被稱爲,我想。)我得到正確的數字,我很確定我有概念下來,我遇到的問題是(?!),它當我嘗試重新分配變量拋出一個錯誤
下面是代碼:
circPrimeCompare(Below, NumCirc):-
RealNum is 0,
circPrimeCompare(1, Below, RealNum, []),
print('R: '),
print(RealNum),
nl,
(NumCirc =:= RealNum).
circPrimeCompare(_, 0, _, _).
circPrimeCompare(N, 1, _, _):- prime(N), print('aaa').
circPrimeCompare(X, Below, RealNum, L):-
(prime(X), X<Below ->
print(X),
nl,
numDigits(X, Y),
rotate(X, Y, N2),
( prime(N2)
-> RealNum2 is RealNum + 1
; RealNum2 is RealNum
),
X2 is X + 1,
( not(circPrimeCompare(X2, Below, RealNum2, L))
-> RealNum = RealNum2, print(RealNum), nl
; RealNum = RealNum2, print(RealNum), nl
),
print('RealNum2: '),
print(RealNum),
nl
;
(X<Below ->
X2 is X + 1,
RealNumPass is RealNum,
( not(circPrimeCompare(X2, Below, RealNumPass, L))
-> RealNum = RealNumPass, print(RealNum), nl
; RealNum = RealNumPass, print(RealNum), nl
),
print('RealNum: '),
print(RealNum),
nl
)
).
這裏是跟蹤:
Fail: (26) circPrimeCompare(10, 10, 4, []) ? creep
^ Exit: (25) not(user:circPrimeCompare(10, 10, 4, [])) ? creep
Call: (25) 4=4 ? creep
Exit: (25) 4=4 ? creep
...
Exit: (24) circPrimeCompare(9, 10, 4, []) ? creep
^ Fail: (23) not(user:circPrimeCompare(9, 10, 4, [])) ? creep
Call: (23) 4=4 ? creep
Exit: (23) 4=4 ? creep
...
Exit: (22) circPrimeCompare(8, 10, 4, []) ? creep
^ Fail: (21) not(user:circPrimeCompare(8, 10, 4, [])) ? creep
**Call: (21) 3=4 ? creep
Fail: (21) 3=4 ? creep**
Redo: (21) numDigits(7, _G589) ? creep
加粗的PA rt是什麼在扔我。我真的不明白爲什麼這樣做。是否因爲變量本質上只是一個用途?任何想法如何解決它?
(。是的,我意識到這是真的,真的很可怕的代碼,我從來沒有這個任務之前寫的序言中的任何東西)
你已經知道跟蹤。擺脫所有'print(...),nl'。你的代碼看起來會更清晰。 – CapelliC 2013-04-29 16:09:03
回溯和遞歸是完全不同的,正交的概念,Prolog沒有變量重新分配。 – 2013-04-29 16:10:05
你應該在每個謂詞附近有簡短的註釋,描述它的目的,以及它的理由應該是什麼。 – 2013-04-29 16:20:02