Alan: 

Thanks. This solution actually may work for me. Although I think the 
recursive call in theory may run out of stack, my tree won't be close to 
that kind of depth.

On Saturday, July 7, 2012 2:52:03 AM UTC-4, Alan Malloy wrote:
>
> If the value is something easy to compute, like a backreference in a tree, 
> and you only need it while walking, why bother to store it at all? 
> Especially if you're going to need to use mutable state, which will make 
> your whole tree less useful for all kinds of things. Here's an example, in 
> which I imagine that your walk wants to update each node so that its value 
> is the sum of its old value, its parent's old value, and its children's old 
> values - you can adjust what goes where if you want one or the other of 
> these directions to see new values instead of old values.
>
> (defn transform [parent node]
>   {:value (apply + (get parent :value 0)        ;; the parent's value, or 
> zero
>                  (:value node)                  ;; the node's old value
>                  (map :value (:children node))) ;; the children's sum
>    :children (map (partial transform node)
>                   (:children node))})
>
> (transform nil {:value 1 
>                 :children [{:value 2} 
>                            {:value 3
>                             :children [{:value 4}]}]})
>
> {:value 6, ;; 1 for old value, 2+3 for children
>  :children ({:value 3, ;; 2 for old value, 1 for parent
>              :children ()}
>             {:value 8, ;; 3 for old value, 1 for parent, 4 for children
>              :children ({:value 7, ;; 4 for old value, 3 for parent
>                          :children ()})})}
>
> On Friday, July 6, 2012 4:56:22 PM UTC-7, Warren Lynn wrote:
>>
>> Hi, Phil:
>>
>> Thanks for your detailed analysis. 
>>
>> My use-case is I have a tree and want to walk over the tree and apply a 
>> function on the nodes. The operation of the function also depends on the 
>> parent and children of the node, so it will be nice if each node already 
>> contains the references to its parent and children. Something like that.
>>
>> I guess I will just use atoms to hold the reference. I am not in pursuit 
>> of pure functional programming, so if it is too much trouble to do it with 
>> FP, I will take whatever works.
>>
>>
>>
>>
>>

-- 
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

Reply via email to