Prolog 递归和累加器 [英] Prolog recursion and accumulators

查看:75
本文介绍了Prolog 递归和累加器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Prolog programming. I am doing recursive classification predicate with accumulator (I believe I need accumulator). Suppose I have following rules:

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).

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

I need classification predicate that returns hierarchy of classes for given specie. Here is what I do:

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,[]).

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

Here is sample how it should work:

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

我改进了我的代码.现在它似乎根据跟踪工作.但什么也没有返回.

I improved my code. Now it seems to work according to trace. But nothing is returned.

推荐答案

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

based only on hierarchical description (since species/1 seems at least a misunderstanding of the complex terminology involved in biology)

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

收益

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

编辑

如果你有兴趣,这个片段

in case you're interested, this snippet

:- 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 文件

produces this SVG file

该界面可从 github 获得,需要安装 Graphviz.

The interface is available from github, requires Graphviz installed.

这篇关于Prolog 递归和累加器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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