X-Git-Url: http://nitlanguage.org diff --git a/lib/ordered_tree.nit b/lib/ordered_tree.nit index 32cea45..86940af 100644 --- a/lib/ordered_tree.nit +++ b/lib/ordered_tree.nit @@ -128,7 +128,15 @@ class OrderedTree[E: Object] do var old_parent = parents.get_or_null(e) if old_parent != null then - sub[old_parent].remove(e) + var subs = sub[old_parent] + subs.remove(e) + if subs.is_empty then + # remove the sub when all children are detached + # so that `==` and `hash` are sane + # Otherwise an empty array will be considered + # differently than no array. + sub.keys.remove(old_parent) + end else if roots.has(e) then roots.remove(e) end @@ -139,8 +147,7 @@ class OrderedTree[E: Object] redef fun write_to(stream: Writer) do for r in roots do - stream.write display(r) - stream.write "\n" + write_line(stream, r, "") sub_write_to(stream, r, "") end end @@ -153,15 +160,29 @@ class OrderedTree[E: Object] var last = subs.last for e2 in subs do if e2 != last then - o.write "{prefix}|--{display(e2)}\n" + write_line(o, e2, prefix+"|--") sub_write_to(o, e2, prefix+"| ") else - o.write "{prefix}`--{display(e2)}\n" + write_line(o, e2, prefix+"`--") sub_write_to(o, e2, prefix+" ") end end end + # Write the full line for the element `e` in `o`. + # + # Basically it does: + # + # ~~~nitish + # o.write "{prefix}{display(e)}\n" + # ~~~ + # + # Usually, you should redefine `display` to change the display of an element. + protected fun write_line(o: Writer, e: E, prefix: String) + do + o.write "{prefix}{display(e)}\n" + end + # Sort roots and other elements using a comparator method # This method basically sorts roots then each group of children fun sort_with(comparator: Comparator)