Prolog 中的树 [英] Trees in Prolog

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

问题描述

我正在 Prolog 中学习二叉树.

I am studying binary trees in Prolog.

我知道结构,但我不明白幻灯片中的这段代码:

I know the structure but I don't understand this code in my slides:

binary_tree(void).
binary_tree(tree(_Element,Left,Right)) :-
  binary_tree(Left), binary_tree(Right).

这需要识别树结构.

但空"是代表吗?

我试过这个查询

?- binary_tree(a).
false.

并假设 a 是树的一个节点.

and assume that a is one node of a tree.

我正在关注此资源以进行理解:

I'm following this resource for understanding:

https://sites.google.com/site/prologsite/prolog-问题/4

但与我的幻灯片不同.

有人能澄清一下吗?

推荐答案

void 是一个原子.它不能假设任何值(除了它自己).此外,a 也是一个原子,根据您的谓词定义,它不是一个有效的树.以 a 作为其唯一节点的树将由复合词 tree(a,void,void) 表示:

void is an atom. It cannot assume any values (other than itself). In addition, a, also an atom, is not a valid tree per your predicate definition. A tree with a as its only node would be represented by the compound term tree(a,void,void):

| ?- binary_tree(tree(a,void,void)).

yes

再举一个例子,具有节点 a..g 的平衡树将用术语表示(为了便于阅读而缩进):

As another example, a balanced tree with nodes a..g would be represented by the term (written indented just for readability):

   tree(a,
       tree(b,
           tree(d,void,void),
           tree(e,void,void)
       ),
       tree(c,
           tree(f,void,void),
           tree(g,void,void)
       )
    )

您可以使用您的 binary_tree/1 谓词再次验证该术语是一棵树:

You can verify that this term is a tree again using your binary_tree /1 predicate:

| ?- binary_tree(tree(a,tree(b,tree(d,void,void),tree(e,void,void)),tree(c,tree(f,void,void),tree(g,void,void)))).

yes

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

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