由於這是家庭作業,我不會給你完整的解決方案。
當您的謂詞擊中匹配node(leaf, _, leaf)
的節點時,它首先執行第二個子句。那會返回一個。然後,當您要求它回溯時,它也會執行第三個條款,因爲也匹配LT=leaf
和RT=leaf
的輸入,所以它會遞歸兩次並且兩次都擊中leaf
的情況。
下一次,如果你要調試這樣的問題自己,trace/1
是一個很好的工具:(它說creep
,我按輸入)
2 ?- trace.
true.
[trace] 2 ?- btree_height(node(node(leaf, x, leaf), x, node(leaf, x, leaf)), H).
Call: (6) btree_height(node(node(leaf, x, leaf), x, node(leaf, x, leaf)), _G821) ? creep
Call: (7) btree_height(node(leaf, x, leaf), _G903) ? creep
Exit: (7) btree_height(node(leaf, x, leaf), 1) ? creep
Call: (7) btree_height(node(leaf, x, leaf), _G903) ? creep
Exit: (7) btree_height(node(leaf, x, leaf), 1) ? creep
Call: (7) _G821 is max(1, 1)+1 ? creep
Exit: (7) 2 is max(1, 1)+1 ? creep
Exit: (6) btree_height(node(node(leaf, x, leaf), x, node(leaf, x, leaf)), 2) ? creep
H = 2 ;
Redo: (7) btree_height(node(leaf, x, leaf), _G903) ? creep
Call: (8) btree_height(leaf, _G903) ? creep
Exit: (8) btree_height(leaf, 0) ? creep
Call: (8) btree_height(leaf, _G903) ? creep
Exit: (8) btree_height(leaf, 0) ? creep
Call: (8) _G911 is max(0, 0)+1 ? creep
Exit: (8) 1 is max(0, 0)+1 ? creep
Exit: (7) btree_height(node(leaf, x, leaf), 1) ? creep
Call: (7) _G821 is max(1, 1)+1 ? creep
Exit: (7) 2 is max(1, 1)+1 ? creep
Exit: (6) btree_height(node(node(leaf, x, leaf), x, node(leaf, x, leaf)), 2) ? creep
H = 2
注我刪除'homework'標記[因爲它已被正式棄用](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated) – kaveman