序言:“findall"对于有限数量的解决方案

编程入门 行业动态 更新时间:2024-10-07 10:20:04
本文介绍了序言:“findall"对于有限数量的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我想找到一个谓词的所有解的总和,我就可以使用

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"对于有限数量的解决方案

本文发布于:2023-11-29 09:12:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序言   数量   解决方案   quot   findall

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!