如何在序言中计算序言中父母的孩子数(不使用列表)? [英] How to count the number of children of parents in prolog (without using lists) in prolog?

查看:59
本文介绍了如何在序言中计算序言中父母的孩子数(不使用列表)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.我有一定数量的事实,例如:父母(简,迪克).父母(迈克尔,迪克).我想要一个谓词,例如:儿童数量(迈克尔,X)所以如果我这样称呼它,它会显示 X=1.

我在网上搜了一下,大家都把孩子放在列表里,有没有不使用列表的方法?

解决方案

计算解决方案的数量需要一些额外的逻辑工具(它本质上是非单调的).这是一个可能的解决方案:

<预><代码>:- 动态 count_solutions_store/1.count_solutions(目标,N):-断言(count_solutions_store(0)),重复,(呼叫(目标),收回(count_solutions_store(SoFar)),更新的是 SoFar + 1,断言(count_solutions_store(更新)),失败;收回(count_solutions_store(T))),!,N = T.

I have the following problem. I have a certain number of facts such as: parent(jane,dick). parent(michael,dick). And I want to have a predicate such as: numberofchildren(michael,X) so that if I call it like that it shows X=1.

I've searched the web and everyone puts the children into lists, is there a way not to use lists?

解决方案

Counting number of solutions requires some extra logical tool (it's inherently non monotonic). Here a possible solution:


:- dynamic count_solutions_store/1.

count_solutions(Goal, N) :-
    assert(count_solutions_store(0)),
    repeat,
    (   call(Goal),
        retract(count_solutions_store(SoFar)),
        Updated is SoFar + 1,
        assert(count_solutions_store(Updated)),
        fail
    ;   retract(count_solutions_store(T))
    ),
    !, N = T.

这篇关于如何在序言中计算序言中父母的孩子数(不使用列表)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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