fernandohur
fernandohur

Reputation: 7144

Mutable tree to persistent tree

Learning Clojure (and Functional Programming) I have stumbled upon the problem of converting a mutable n-ary tree represented as nested java.util.ArrayLists into a persistent tree.

Using non-functional programming you would normally create the tree from the root to the leaves. This does not seem to be possible using persistent data structures.

Can someone show me how to construct an immutable tree given a mutable n-ary tree?

Upvotes: 2

Views: 126

Answers (1)

amalloy
amalloy

Reputation: 91877

As with most things functional, the answer is recursion. It's in fact tremendously easier to do functionally than it would be to do by mutating a bunch of lists of lists in java. You just define a function that converts a single ArrayList into a clojure list, and then have that function call itself recursively on any sub-lists. Here's the easiest answer; you can add frills if you want to support maps instead of lists or whatever.

(import '(java.util List ArrayList))
(defn lists->tree [x]
  (if (instance? List x)
    (map lists->tree x)
    x))

(lists->tree (ArrayList. [(ArrayList. [1 2 3])
                          (ArrayList. [(ArrayList. [4 5])
                                       (ArrayList. [6])])]))
((1 2 3) ((4 5) (6)))

Upvotes: 2

Related Questions