简体   繁体   English

二元树作为嵌入对

[英]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. 我将使用SML语法作为示例。 This is my btree type definition: 这是我的btree类型定义:

datatype btree = leaf | branch of btree*btree;

So, I'd like to write a function that, given a btree, print the following: 所以,我想写一个函数,给定一个btree,打印以下内容:

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. 这显然是SML的问题,也许是其他功能语言的问题。

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 . 因为您要做的就是将树结构打印到屏幕上,您可以这样做,并将函数的返回类型设置为unit That is instead of trying to return the tuple (0, (0, 0)) just print the string (0, (0, 0)) to the screen. 这不是试图返回元组(0, (0, 0))只是将字符串(0,(0,0 (0, (0, 0))打印到屏幕。 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: 如果您还希望能够获得表示btree的字符串,那么天真的解决方案将是:

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. 但是,我并不真的推荐这种变体,因为对于大btree来说,由于许多字符串连接存在问题。

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. 值得思考的是以下变体,它通过一个技巧(例如也在Haskell的Show类中使用)避免了连接问题,即,不是处理字符串,而是处理从char列表到char列表的函数。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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