LISP - 树(Tree)

LISP - 树(Tree) 首页 / LISP入门教程 / LISP - 树(Tree)

您可以从cons单元构建树数据结构,作为列表列表,如,二叉树的预顺序,顺序和后顺序。

让我们考虑由cons单元组成的树结构,这些结构形成以下列表列表-

((1 2)(3 4)(5 6))。

以图表形式,它可以表示为-

Tree Structure

Tree函数

尽管大多数情况下,您将需要根据特定需要编写自己的树函数,但是LISP提供了一些可以使用的树函数。

除了所有列表函数,以下函数尤其适用于树结构-

Sr.No.Function & 描述
1

copy-tree x & optional vecp

它返回cons单元格x的树的副本。

2

tree-equal x y & key :test :test-not :key

它比较了两个cons细胞树。如果x和y都是缺点单元格,则将它们的汽车和cdrs进行递归比较。如果x和y都不是约束单元格,则将它们通过eql进行比较,或根据指定的测试进行比较。 :key函数(如果已指定)将应用于两棵树的元素。

链接:https://www.learnfk.comhttps://www.learnfk.com/lisp/lisp-tree.html

来源:LearnFk无涯教程网

3

subst new old tree & key :test :test-not :key

它用 tree 中的 new 项替换给定的旧项的出现,该树是con单元格的树。

4

nsubst new old tree & key :test :test-not :key

它的作用与替换相同,但会破坏原始树。

5

sublis alist tree & key :test :test-not :key

它像subst一样工作,除了它需要新旧对的关联列表 alist 。

6

nsublis alist tree & key :test :test-not :key

它与sublis相同,但具有破坏性。

Tree - 示例1

创建一个名为main.lisp的新源代码文件,然后在其中键入以下代码。

(setq lst (list '(1 2) '(3 4) '(5 6)))
(setq mylst (copy-list lst))
(setq tr (copy-tree lst))

(write lst)
(terpri)
(write mylst)
(terpri)
(write tr)

当您执行代码时,它返回以下输出-

((1 2) (3 4) (5 6))
((1 2) (3 4) (5 6))
((1 2) (3 4) (5 6))

Tree - 示例2

创建一个名为main.lisp的新源代码文件,然后在其中键入以下代码。

(setq tr '((1 2 (3 4 5) ((7 8) (7 8 9)))))
(write tr)
(setq trs (subst 7 1 tr))
(terpri)
(write trs)

当您执行代码时,它返回以下输出-

((1 2 (3 4 5) ((7 8) (7 8 9))))
((7 2 (3 4 5) ((7 8) (7 8 9))))

创建Tree树

让我们尝试使用LISP中可用的列表函数来构建自己的树。

首先让我们创建一个包含一些数据的新节点

(defun make-tree (item)
   "it creates a new node with item."
   (cons (cons item nil) nil)
)

接下来,让我们在树中添加一个子节点-它需要两个树节点,并将第二个树添加为第一个树的子节点。

(defun add-child (tree child)
   (setf (car tree) (append (car tree) child))
   tree)

此函数将给第一个子节点返回一棵给定的树-它将获取一个树节点并返回该节点的第一个子节点;如果该节点没有任何子节点,则返回nil。

(defun first-child (tree)
   (if (null tree)
      nil
      (cdr (car tree))
   )
)

此函数将返回给定节点的下一个同级节点-它以树节点为参数,并返回对下一个同级节点的引用;如果该节点不包含任何节点,则返回nil。

(defun next-sibling (tree)
   (cdr tree)
)

最后,我们需要一个函数来返回节点中的信息-

(defun data (tree)
   (car (car tree))
)

Tree树 - 示例

创建一个名为main.lisp的新源代码文件,然后在其中键入以下代码。

(defun make-tree (item)
   "it creates a new node with item."
   (cons (cons item nil) nil)
)
(defun first-child (tree)
   (if (null tree)
      nil
      (cdr (car tree))
   )
)

(defun next-sibling (tree)
   (cdr tree)
)
(defun data (tree)
   (car (car tree))
)
(defun add-child (tree child)
   (setf (car tree) (append (car tree) child))
   tree
)

(setq tr '((1 2 (3 4 5) ((7 8) (7 8 9)))))
(setq mytree (make-tree 10))

(write (data mytree))
(terpri)
(write (first-child tr))
(terpri)
(setq newtree (add-child tr mytree))
(terpri)
(write newtree)

当您执行代码时,它返回以下输出-

10
(2 (3 4 5) ((7 8) (7 8 9)))

((1 2 (3 4 5) ((7 8) (7 8 9)) (10)))

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

微服务架构核心20讲 -〔杨波〕

10x程序员工作法 -〔郑晔〕

ZooKeeper实战与源码剖析 -〔么敬国〕

职场求生攻略 -〔臧萌〕

爆款文案修炼手册 -〔乐剑峰〕

讲好故事 -〔涵柏〕

现代React Web开发实战 -〔宋一玮〕

结构执行力 -〔李忠秋〕

AI大模型系统实战 -〔Tyler〕

好记忆不如烂笔头。留下您的足迹吧 :)