这是如何计算的?我试图了解如何在列表中分配H的值 [英] How does this compute ? I am trying to understand how the values of H get assigned in the list

查看:63
本文介绍了这是如何计算的?我试图了解如何在列表中分配H的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此谓词应打印大小为N的列表,其中包含01的可能排列.

This predicate should print a list of size N containing possible permutations of 0 and 1.

我的问题是:H的值是否在每次递归中都被保留,还是使用bit(H)值创建列表的过程是在回溯阶段进行的?

My question is : does the value of H get carried over with each recursion or does the creation of the list with values of bit(H) take place in the backtracking phase?

bit(0).
bit(1).
gen(0,[]).
gen(N,[H|T]) :-
   N > 0,
   bit(H),
   N1 is N - 1,
   gen(N1,T).

推荐答案

序言执行完全与选择点有关.在这里,每个递归步骤的bit/1谓词都留下一个选择点. 当您要求Prolog为您提供其他解决方案时,它将回到最年轻的选择点.在这里,它不会通过bit/1的第一个子句并将H绑定到0,而是将通过第二个子句并将H绑定到1.选中这两个子句后,Prolog将返回到较早的选择点,依此类推,直到最终所有选择点都用尽,程序返回false..

Prolog execution is all about choice points. Here a choice point is left at each recursion step by the bit/1 predicate. When you ask Prolog to give you another solution, it will just go back to the youngest choice point. Here, instead of going through the first clause of bit/1 and bind H to 0, it will go through the second clause and bind H to 1. Once both clauses have been picked, Prolog'll go back to an older choice point, etc... until ultimately all choice points are exhausted and the program returns false..

您可以使用trace/0谓词自己尝试:

you can try this yourself with the trace/0 predicate:

?- trace, gen(3, Result).

这篇关于这是如何计算的?我试图了解如何在列表中分配H的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆