On 18.08.2013 16:51, Hussein B. wrote: > Would you please help me transforming this imperative code into > functional one? > > The code is a typical snippet in imperative style. A lot of mutations > that I don't even know how to start morphing it to Clojure. > > class Container { > Map<String, Container> children; > String letter; > List<String> value; > } > > void insert(Container container, String letters, String value) { > > for (int i = 0; i < letters.length; i++) { > > String letter = new String(letters.chatAt[i]); > > if (container.children.get(letter) != null) { > container = container.children.get(letter); > } else { > Map<Container> childContainer = new HashMap<>(); > container.children.put(letter, childContainer); > container = container.children.get(letter); > } > > if (i == letters.length() - 1) { > container.values.add(value); > break; > } > > }
(You don't provide example inputs and outputs for the method, so I may have misunderstood the code. If that's the case please disregard the next paragraph.) This example may be to artificial to be translated into Clojure. What use is it to store strings in a tree keyed by the string's characters? If you know the path to the string, you already know the string itself, and you don't need the tree at all! It is rarely a good idea to directly translate code from one language into a much different one. It may be done, but the end result will not be pretty and it certainly won't be idiomatic. I'm sure you'll get much more helpful responses if you ask a question of the form "I need to solve this problem – how can I do it in Clojure?" If what you want is to manipulate trees in a purely functional way, you might want to check out the Zipper data structure. [1] You can find it in Clojure's standard library in the namespace `clojure.zip`. [2] [1] http://www.st.cs.uni-saarland.de/edu/seminare/2005/advanced-fp/docs/huet-zipper.pdf [2] http://richhickey.github.io/clojure/clojure.zip-api.html Hope this helps, -- Timo -- -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups "Clojure" group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/groups/opt_out.