作业是接受两个变量,一个介于 0 和 10,000 之间的数字,以及在 1 和该数字之间有多少个圆素数。
我在通过递归传递变量时遇到了麻烦(我认为回溯就是所谓的。)我得到了正确的数字,我很确定我已经把这个概念记下来了,我遇到的问题是它抛出了一个当我尝试重新分配变量时出错(?!)
这是代码:
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
粗体部分是让我失望的部分。我真的不明白为什么它会这样。是因为变量本质上只是一种用途吗?关于如何解决它的任何想法?
(是的,我意识到这是非常非常糟糕的代码。在这个任务之前我从来没有在 Prolog 中写过任何东西。)