How to print a tree structure into a string fast in Ocaml?

ε祈祈猫儿з 提交于 2019-12-05 07:47:50

Use a string Buffer.

^ is defined as,

let (^) s1 s2 =
  let l1 = string_length s1 and l2 = string_length s2 in
  let s = string_create (l1 + l2) in
  string_blit s1 0 s 0 l1;
  string_blit s2 0 s l1 l2;
  s

What you are doing is creating a new string each time and copying the old values in. Pretty much standard in any language where strings are represented as character arrays. The hangup happens because you are doing this FOUR times for each node (there isn't an optimization for multiple ^ calls)! As for a buffer, it will create a giant string and continually fill it in as managed by the data structure,

 type t =
   {mutable buffer : string;
    mutable position : int;
    mutable length : int;
    initial_buffer : string}

Even if you decide to create the initial buffer size to 1, the resize function will adjust the size in a way that will limit the number of re-allocations. For example, the add_string function will increase the size of the array by len*2^(n+p-len), where n is the length of the new string, p is the position and len is the length of the original buffer --only if the buffer cannot support the string, of course. So, the size of the buffer grows exponentially and there will be few re-allocations as things progress. Of course, it's best to set the initial buffer to something reasonable, but it isn't necessary.

The new convert function wouldn't look much more verbose:

let rec convert buf ex =
  let addb = Buffer.add_string buf in
  match ex with
   Number i -> addb (string_of_int i)
  |Plus (a,b) -> (addb "(+ "; convert buf a; addb " "; convert buf b; addb ")")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!