簡體   English   中英

二元樹作為嵌入對

[英]Binary trees as innested pairs

我試圖將一般的二叉樹表示為一對。

我將使用SML語法作為示例。 這是我的btree類型定義:

datatype btree = leaf | branch of btree*btree;

所以,我想寫一個函數,給定一個btree,打印以下內容:

bprint leaf = 0
bprint (branch (leaf,leaf)) = (0,0)
bprint (branch (leaf, branch (leaf,leaf))) = (0, (0, 0))

等等。

問題是這個函數總是返回不同的類型。 這顯然是SML的問題,也許是其他功能語言的問題。

任何想法?

因為您要做的就是將樹結構打印到屏幕上,您可以這樣做,並將函數的返回類型設置為unit 這不是試圖返回元組(0, (0, 0))只是將字符串(0,(0,0 (0, (0, 0))打印到屏幕。 這樣你就不會遇到任何類型的困難。

如果你真的不需要其他地方的字符串表示,正如其他人已經提到的那樣,只需打印樹就可能是最簡單的方法:

open TextIO

datatype btree = leaf | branch of btree * btree

fun print_btree leaf = print "0"
  | print_btree (branch (s, t)) =
    (print "("; print_btree s; print ", "; print_btree t; print ")")

如果您還希望能夠獲得表示btree的字符串,那么天真的解決方案將是:

fun btree_to_string leaf = "0"
  | btree_to_string (branch (s, t)) =
    "(" ^ btree_to_string s ^ ", " ^ btree_to_string t ^ ")"

但是,我並不真的推薦這種變體,因為對於大btree來說,由於許多字符串連接存在問題。

值得思考的是以下變體,它通過一個技巧(例如也在Haskell的Show類中使用)避免了連接問題,即,不是處理字符串,而是處理從char列表到char列表的函數。 然后可以用函數組合代替連接

fun btree_to_string' t =
  let
    fun add s t = s @ t
    fun add_btree leaf = add [#"0"]
      | add_btree (branch (s, t)) =
        add [#"("] o add_btree s o add [#",", #" "] o add_btree t o add [#")"]
  in implode (add_btree t []) end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM