Skip to content
Tcl Source Code Ticket Change Details
Login

Ticket Change Details

Overview

Artifact ID: 37cacac0db16041b9a067e434bd7dd86a7514e95
Ticket: 9ec7bd5f329df1ff790266b3c318a837ac32895e
Some way to modify complex data structures efficiently
User & Date: ferrieux on 2015-05-09 08:59:18
Changes

  1. icomment:
    The reason why we modify the copy, is that there are still live references to the original instance (refcount>1). It turns out that there is no other sound way to do it, given the string semantics of the language (look for "Mutability patch" in comp.lang.tcl archives to witness a failed attempt to wander off).
    
     Most Tcl list-manipulation primitives are optimized to work in-place when refcount is 1. So, when it matters, arrange for refcount to be 1. Note this is not trivial. Two gotchas:
    
      - don't pass the value-to-be-modified-in-place as proc args, because it will add references from the (live) call stack, which you cannot nuke.
    
      - use the "K-free-K trick" (like the K combinator, without defining it): assuming the last reference is in the (local) var "x" holding it, pass the value 
    
         $x[unset x]
    
    to the list-manipulation primitive. E.g, for in-place truncation:
    
         set x [lrange $x[unset x] 0 1000]
    
    The case of pass-by-varname primitives is a bit different. Lset is one such beast. The copy-on-write principle applies all the same, except that there is no need to unset the var (nor is it an option, since we're passing a varname !), but you still need to make sure the var is the only remaining reference. When this is so, a [representation $x] yields a refcount of 2 (one for the var, and one for the stack reference, i.e. the argument passed to [representation]).
    
    In your case, $subnode has a refcount of 3 because one reference remains in the containing dict. This prevents lset from working in-place. Again, when it matters, explicit ref surgery is due. In your case, temporarily severe the subnode from its container:
    
         set subnode [dict get $complex_datastructure c]
         dict unset complex_datastructure c
         lset subnode 0 10
         dict set complex_datastructure c $subnode
    
    Note that, contrarily to the K-free-K, this idiom can be hidden in a utility function, since the important value is deep inside a container rather than passed as an argument.
    
    Summary: such tricks
    
          - are a necessary evil due to the value semantics in Tcl;
          - have a cost in terms of code complexity, and should be pulled only when it matters, ie for big values;
          - don't have a fixed or obvious indexing algorithm (what if the value is buried in a dict-of-lists-of-dict ?)
    
    
    For these reasons, ad hoc code like the above will always be the best approach, on a case-by-case basis, and no magical primitive in the core will ease that. Hence, closing, sorry.
    
  2. login: "ferrieux"
  3. mimetype: "text/plain"