Prolog 递归和累加器

编程入门 行业动态 更新时间:2024-10-21 16:15:43
本文介绍了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 递归和累加器

本文发布于:2023-11-30 03:17:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648545.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   累加器   Prolog

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!