简体   繁体   中英

Binary trees as innested pairs

I'm trying to represent a generic binary tree as a pair.

I'll use the SML syntax as example. This is my btree type definition:

datatype btree = leaf | branch of btree*btree;

So, I'd like to write a function that, given a btree, print the following:

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

and so on.

The problem is that this function always return different types. This is obviously a problem for SML and maybe for other functional languages.

Any idea?

Since all you want to do is to print the tree structure to the screen, you can just do that and have your function's return type be unit . That is instead of trying to return the tuple (0, (0, 0)) just print the string (0, (0, 0)) to the screen. This way you won't run into any difficulties with types.

If you really do not need a string representation anywhere else, as already mentioned by others, just printing the tree might be the easiest way:

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

In case you also want to be able to obtain a string representing a btree , the naive solution would be:

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

However, I do not really recommend this variant since for big btree s there is a problem due to the many string concatenations.

Something nice to think about is the following variant, which avoids the concatenation problem by a trick (that is for example also used in Haskell's Show class), ie, instead of working on strings, work on functions from char lists to char lists. Then concatenation can be replaced by function composition

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM