如果你有这些事实:
parent(albert, bob). parent(albert, betsy). parent(albert, bill). parent(alice, bob). parent(alice, betsy). parent(alice, bill). parent(bob, carl). parent(bob, charlie).然后这段代码:
grand_parent(X, Y) :- parent(Z, X), parent(Y, Z).如果你输入:
grand_parent(carl, A)然后它返回:
A = albert ? ; A = alice ? ; no这个怎么用? 这有点令人困惑。 特别是“Z”部分。
If you have these facts:
parent(albert, bob). parent(albert, betsy). parent(albert, bill). parent(alice, bob). parent(alice, betsy). parent(alice, bill). parent(bob, carl). parent(bob, charlie).And then this code:
grand_parent(X, Y) :- parent(Z, X), parent(Y, Z).And if you type:
grand_parent(carl, A)Then it returns:
A = albert ? ; A = alice ? ; noHow does this work? It's a bit confusing. Especially the "Z" part.
最满意答案
我敢打赌,如果你使用更好的变量名,它看起来就不那么混乱
grand_parent(Grandchild, Grandparent) :- parent(Parent, Grandchild), parent(Grandparent, Parent).你看到当你询问查询grand_parent(carl, X) ,Prolog将找到grand_parent/2的定义并将carl替换为grand_parent/2 。 为了证明这一点,它必须证明parent(Parent, carl) 。 好吧,这成功了一次,将Parent与bob统一起来。 逗号的作用类似于“和”,所以现在Prolog必须证明parent(Grandparent, bob) 。 它取得了成功,将Grandparent与albert统一起来。 Prolog总是按照你提供事实的顺序搜索数据库,这就是为什么我们在获得Alice之前得到Albert的原因。
当你击中; 就像你和Prolog谈话而你说“或者?” 好像要提示另一个解决方案。 所以Prolog会回到最后一个选择点并开始向前扫描。 最后一个选择点是parent(Grandparent, bob)所以它向前扫描,直到找到成功的parent(alice, bob) ,将Grandparent与alice统一起来。 您要求它提供另一种解决方案,它将耗尽所有可能的parent(Grandparent, bob)所以它将备份到parent(Parent, carl) ,它没有找到任何更多的解决方案。 那时Prolog说错了,因为这是出于想法。
希望这可以帮助!
I bet it looks less confusing if you use better variable names:
grand_parent(Grandchild, Grandparent) :- parent(Parent, Grandchild), parent(Grandparent, Parent).You see when you ask the query grand_parent(carl, X), Prolog is going to find the definition of grand_parent/2 and substitute carl for Grandchild. To prove this, it has to prove parent(Parent, carl). Well, this succeeds once, unifying Parent with bob. The comma works like "and", so now Prolog has to prove parent(Grandparent, bob). It succeeds, unifying Grandparent with albert. Prolog always searches the database in the order you supply it with facts, that's why we got Albert before we get Alice.
When you hit ; it's like you're having a conversation with Prolog and you're saying "or?" as if to prompt it for another solution. So Prolog backs up to the last choice point and starts scanning forward. The last choice point was in parent(Grandparent, bob) so it scans forward until it finds parent(alice, bob) which succeeds, unifying Grandparent with alice. You ask it for another solution and it will exhaust all the possibilities with parent(Grandparent, bob) so it will back up to parent(Parent, carl), which doesn't find any more solutions. At that point Prolog says false because it's out of ideas.
Hope this helps!
更多推荐
发布评论