gpt4 book ai didi

prolog - 从 prolog 查询中返回第 N 个最老的子项

转载 作者:行者123 更新时间:2023-12-02 19:08:59 29 4
gpt4 key购买 nike

child(john, mary).
child(john, martinez).
child(john, maggie).

age(mary, 11).
age(martinez, 12).
age(maggie, 13).

我想做的是定义一个查询,返回一个人的第 N 个最大的 child ,在本例中是 John。例如。第一个最年长的是玛吉。第二大的是马丁内斯,第三大的是玛丽。

我是 prolog 新手,网站上提供的教程是用一些过时的 flash 脚本编写的,这些脚本早已过时且不受支持,所以我在这里有点一无所知。预先感谢您对此提供的帮助。

最佳答案

比较 children 的年龄。 P与<、>或=统一

ch_compare(P, C1, C2) :- age(C1, A1), age(C2, A2), compare(P, A2, A1).

收集所有 child ,对它们进行排序,然后选择第 n 个最大的。

nth_child_of(N, Parent, Child) :-
findall(C, child(Parent, C), Children),
predsort(ch_compare, Children, Sorted),
nth1(N, Sorted, Child).

我建议您阅读谓词 findall/3predsort/3

编辑:如果您想要按年龄排序的 child 列表,那么您有

ch_compare(P, C1, C2) :- age(C1, A1), age(C2, A2), compare(P, A2, A1).
children(Parent, Children) :-
findall(C, child(Parent, C), Unsorted),
predsort(ch_compare, Unsorted, Children).

关于prolog - 从 prolog 查询中返回第 N 个最老的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64620033/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com