Trees in Prolog

坚强是说给别人听的谎言 提交于 2019-12-11 10:25:34

问题


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

This would need for recognize the tree structure.

But does "void" represent?

I tried this query

?- binary_tree(a).
false.

and assume that a is one node of a tree.

I'm following this resource for understanding:

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

but is different to my slides.

Can anyone clarify this?


回答1:


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

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

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


来源:https://stackoverflow.com/questions/53829509/trees-in-prolog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!