私はPrologから始めています、そして私は少し混乱しています...
私は簡単なプログラムを持っています:
sum(0, []).
sum(Total, [Head|Tail]) :- sum(Sum, Tail), Total is Head + Sum.
デバッグすると、Prologが最初にリストをHeadとTailで分割するので、結果は0 +空のリストになり、その後、数値の合計が開始され、リストに再度追加されます。
誰かがそれが最初に来ない理由を説明しTotal is Head + Sum.
、次にリストを再び頭と尾に分割することができますか?
編集:ここにトレースがあります:
[trace] ?- sum(X, [1,2,3]).
Call: (6) sum(_G345, [1, 2, 3]) ? creep
Call: (7) sum(_G424, [2, 3]) ? creep
Call: (8) sum(_G424, [3]) ? creep
Call: (9) sum(_G424, []) ? creep
Exit: (9) sum(0, []) ? creep
Call: (9) _G430 is 3+0 ? creep
Exit: (9) 3 is 3+0 ? creep
Exit: (8) sum(3, [3]) ? creep
Call: (8) _G433 is 2+3 ? creep
xit: (8) 5 is 2+3 ? creep
Exit: (7) sum(5, [2, 3]) ? creep
Call: (7) _G345 is 1+5 ? creep
Exit: (7) 6 is 1+5 ? creep
Exit: (6) sum(6, [1, 2, 3]) ? creep
X = 6.