序言:“findall"对于有限数量的解决方案 [英] Prolog: "findall" for limited number of solutions

查看:51
本文介绍了序言:“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"对于有限数量的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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