Prolog 递归和累加器

标签 prolog

我是 Prolog 编程新手。我正在使用累加器进行递归分类谓词(我相信我需要累加器)。假设我有以下规则:

species(tiger).
species(carnivora).
species(ferae).
species(scrotifera).
species(laurasiatheria).

isa(tiger,carnivora).
isa(carnivora,ferae).
isa(ferae,scrotifera).
isa(scrotifera,laurasiatheria).
isa(laurasiatheria, mammalia).

我需要返回给定物种的类层次结构的分类谓词。这是我所做的:

classification_aux(mammalia,[H|T],[]).
classification_aux(Specie, Class, Accum) :-
    isa(Specie, Y),
    classification_aux(Y, [Y|Class], Accum).    

classification(Specie, Class) :- classification_aux(Specie,Class,[]).

这是它应该如何工作的示例:

classification(gray_tree_frog, X).
X = [amphibia, anura, hylidae, hyla].

编辑:我改进了我的代码。现在看来是按照痕迹工作的。但没有返回任何内容。

最佳答案

仅基于分层描述(因为species/1似乎至少是对生物学中涉及的复杂术语的误解)

classification(Specie, Classification) :-
    isa(Specie, Class) ->
      Classification = [Class|SuperClasses],
      classification(Class, SuperClasses)
    ; Classification = [].

产量

?- classification(tiger, X).
X = [carnivora, ferae, scrotifera, laurasiatheria, mammalia].

编辑

如果您有兴趣,请查看此片段

:- use_module(carlo(snippets/genealogy/pqGraphviz_emu)).

classification :-
    graph_window(build_graph, []).

build_graph(G) :-
    forall(species(S), make_node(G, S, [shape=diamond], _)),
    forall(isa(X, Y), (lookup_node(G, X, Xp), lookup_node(G, Y, Yp), new_edge(G, Xp, Yp))).

lookup_node(G, N, Np) :-
    find_node(G, N, Np) -> true ; make_node(G, N, Np).

生成此 SVG 文件

enter image description here

该接口(interface)可从github获得,需要安装 Graphviz。

关于Prolog 递归和累加器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37067612/

相关文章:

list - 在 Prolog 中搜索(相同)两个元素的列表

concurrency - 接收目标列表作为输入的元谓词

algorithm - Prolog 多米诺解决方案

prolog - 序言中的csymf和csym之间的区别

prolog - 访问 prolog 中的程序列表

list - Prolog:在列表中,查找给定元素之后的元素

prolog - Minimax 在 "Prolog Programming for Artificial Intelligence"中实现 - min_to_move/1 和 max_to_move/1 是什么?

prolog - prolog中的选择排序

scala - 你能用 Scala 进行逻辑编程吗?

prolog - 序言中的否定