假设我想找到一个谓词的所有解的总和,我就可以使用
Say I want to find sum of all solutions to a predicate, I just can use
findall(L, find(L), Sols),和 Sols 的 sum 成员.
and just sum members of Sols.
但是,如果 find(L) 有大量(可能是无限的)解,而我只想得到其中的前 10 个呢?
But what if find(L) has a huge number (infinitely, maybe) of solutions, and I just want to get only first 10 of them?
我希望它可以在 B-Prolog 和 ECLiPSe CLP 中使用.
I'd want this to be usable in B-Prolog and ECLiPSe CLP.
推荐答案这就是你在 ECLiPSe 中的做法:
This is how you would do it in ECLiPSe:
find_n(N, Term, Goal, Solutions) :- ( N < 1 -> Solutions = [] ; record_create(Bag), shelf_create(count(N), Counter), ( once(( call(Goal), recordz(Bag, Term), \+shelf_dec(Counter, 1) % succeed if enough )), fail ; recorded_list(Bag, Solutions) ) ).这是可重入的并且不会泄漏内存(两者都是基于全局变量或动态谓词的解决方案的问题).如果您希望它正确处理模块,则需要进行少量添加.
This is reentrant and does not leak memory (both are problems with global variable or dynamic predicate based solutions). Small additions are needed if you want it to deal correctly with modules.
您当然可以使用与 Paulo 使用的 assert/retract 原语相同的代码结构.
You could of course use the same code structure with the assert/retract primitives that Paulo used.
更多推荐
序言:“findall"对于有限数量的解决方案
发布评论