Haskell 通過惰性計算來實現廣度優先編號 Breadth-first Numbering

The code that follows sets up the defining system of equations:

  • Streams (infinite lists) of labels are used as a mediating data structure to allow equations to be set up between adjacent nodes within levels and between the last node at one level and the first node at the next. 標籤流(即:無限列表)用作中間數據結構,以允許在層級內的相鄰節點之間以及一個層級的最後一個節點與下一個層級的第一個節點之間建立方程式。

  • Idea: the tree numbering function for a subtree takes a stream of labels for the first node at each level, and returns a stream of labels for the node after the last node at each level. 想法:子樹的編號函數接收的標籤流給每層的第一個節點,並返回每層的最後一個節點之後的節點的標籤流。

  • As there manifestly are no cyclic dependences among the equations, we can entrust the details of solving them to the lazy evaluation machinery in the safe knowledge that a solution will be found. 由於方程之間顯然沒有循環依賴關係,因此在可以找到解決方案的安全認知下,我們可以將求解它們的細節委託給惰性計算機制。

1、定義廣度優先編號函數bfn
bfn :: Tree a -> Tree Integer 
bfn t = t’ 
	where 
		(ns, t’) = bfnAux (1 : ns) t

2、定義廣度優先編號輔助函數bfnAux
bfnAux :: [Integer] -> Tree a -> ([Integer], Tree Integer)
bfnAux ns Empty = (ns, Empty) 
bfnAux (n:ns) (Node tl _ tr)=((n+1):ns’’, Node tl’ n tr’)
where
	(ns’, tl’) = bfnAux ns tl 
	(ns’’, tr’) = bfnAux ns’ tr
3、遞歸圖解
  • 對於每個節點的編號:
    在這裏插入圖片描述

  • 對於整棵樹的編號:
    在這裏插入圖片描述

4、編號過程
  • ①定義一個用來裝樹的每個節點編號(label)的無窮列表ns,即[1,2,3…].
  • ②將這個列表ns以及需要編號的樹t作爲參數,通過編號輔助函數bfnAux來完成編號,bfnAux返回一個二元組,這個二元組裏裝有無窮列表ns經過編號操作之後的得到的列表ns’’(ns在經過給左子樹編號後得到ns’,ns’再給右子樹編號後得到ns’’)以及編號之後的樹t’.
  • ③對每個節點的編號:首先把ns的第一個元素n取出,將節點編號爲元素n的值。

e.g. 以下圖爲例:
在這裏插入圖片描述

遍歷根節點(n=1)及其左右子樹:在給根節點編號時,bfnAux將ns [1,2,3,4,5...]寫爲1:[2,3,4,5..],取出第一個元素1編號給根節點,剩下的列表[2,3,4,5...]寫爲2:[3,4,5..],取出第一個元素2編號給根節點的左子樹的根節點,剩下的列表記爲ns' [3,4,5..],寫爲3:[4,5..],取出第一個元素3編號給根節點的右子樹的根節點,剩下的列表記爲ns'' [4,5..],此時bfnAux返回一個二元組,這個二元組的中新的列表ns爲(n+1):ns'',即新列表ns爲 [2,4,5..]

遍歷第二個根節點(n=2)及其左右子樹:在對第一層編號完成之後,bfnAux把編號爲2的左子樹作爲新的根節點進行編號,將新的列表ns [2,4,5]寫爲2:[4,5],取出第一個元素2對已經編過號且編號爲2的根節點再次編號爲2,剩下的列表[4,5..]寫爲4:[5..],取出第一個元素4編號給左子樹,剩下ns' [5..],取出5編號給右子樹,剩下ns'' [6..]... 返回新的列表ns [3,6..]

以此類推...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章