Version 5 of C struct is Tcl!

Updated 2002-10-09 15:32:48

This comes up every so often on comp.lang.tcl:

 Chris Nelson wrote:
 > For example, whereas I might write C like:
 > 
 >     struct s {
 >        int foo
 >        char bar
 >        float grill
 >     } 
 > 
 >     s.foo = 1;
 >     s.bar = 'c';
 >     s.grill = 3.14159;

 proc struct { name thingys } {
     foreach thing $thingys {
        uplevel set $name.$thing \[ list \]
     }
 }

 struct s {
   foo
   bar
   grill
 }

 set s.foo 1
 set s.bar c
 set s.grill 3.14159

Of course, you probably dont just want to init the "struct" to nulls, but to reasonable values:

 proc struct { name thingys } {
     foreach { key value } $thingys {
        uplevel set $name.$key $value 
     } 
 }

 struct s {
   foo 1
   bar c
   grill 3.14159
 }

Tcl has no types, but if you want to create a typing convention and then use types in your struct it is only a matter of adding type to the foreach that now iterates key and value over $thingys. -PSE


So how do I create a linked list, as I would in C?

Ro: Well if you just want a list of objects you could just make a regular tcl list - they grow dynamically. Each element in the list could be a reference to an object... what are you trying to represent?

RS: Lists we have. The purpose of linked lists is often to allow insertion or deletion of elements, which our flat lists allow with linsert, lreplace and (probably most often wanted),lappend. You could simulate a linked list with an array, e.g.

 set a(1,content) "hello world"
 set a(1,prev) 0 ;# "pointer" to previous
 set a(1,next) 2 ;# "pointer" to next element

... but I doubt whether that's more efficient than linsert/lreplace...