Version 2 of Revisiting TOOT with a store

Updated 2012-09-06 16:39:30 by jima

jima 2012-09-06

I remember myself getting lost on TOOT from time to time. Lately I have also come to realise I wanted somewhat "unify" the interface to different data structures in tcl (variable, list, dictionary) under some kind of "store" (an array).

Here is the crossover (thanks to schelte and aspect from tcler's chat who got me in the tracks of info frame). I won't try to explain in words what I've just did, I think the code reflects it quite well already.

By the way, I did not extensively test how this idea merges with variable names that are under some namespace. This is to be considered just a sketch.

 proc store {store_str mode operation key args} {
  set name [lindex [string range [dict get [info frame -1] cmd] 4 end] 0]
  array set store $store_str
  switch $mode {
   var {
    set result [{*}$operation store($key) {*}$args]
   }
   val {
    set result [{*}$operation $store($key) {*}$args]
   }
   inval {
    set result [set store($key) [
     {*}$operation $store($key)[unset store($key)] {*}$args
    ]]
   }
   default {
    error {bad mode} $mode
   }
  }
  uplevel 1 "set $name {store {[array get store]}}"
  set result
 }


 proc test_store_toot {} {
  set a [list store {}]

  puts set_wea([{*}$a var set wea 45])
  puts a($a)

  puts lappend_wea([{*}$a var lappend wea 56])
  puts a($a)

  puts lreplace_wea([{*}$a inval lreplace wea 0 0 99])
  puts a($a)

  puts set_foo_bar_to_zz([{*}$a var {dict set} foo bar zz])
  puts a($a)

  puts get_foo_bar([{*}$a val {dict get} foo bar])
  puts a($a)

  list
 }

 test_store_toot