| Store | Cart

Re: [TCLCORE] Tcl Objects with value semantics

From: Peter S <pete...@gmail.com>
Tue, 28 Jul 2015 14:07:54 +0200
In my opinion,

set a [dict create]
@ a.first = "Fred"
@ a.last = "Flintstone"
@ a.count = 0
set b [@ a.last]

is not necessarily better than:

set a {
	first	Fred
	last	Flintstone
	count	0
}
set b [dict get $a last]

To define methods only valid until the dict goes out of scope, here is
an equivalent alternative without apply:

# define a method stored in the dict
proc dictMethod {dictName name args body} {
	upvar $dictName dict
	dict set dict method_$name [list $args $body]
	return
}

# call method in dict
proc dictCall {dictName name args} {
	upvar $dictName this
	lassign [dict get $this method_$name] method_args body
	if {[llength $args] != [llength $method_args]} {
		error "args should be: $method_args"
	}
	# assign arguments to variables
	foreach arg $args method_arg $method_args {
		set $method_arg $arg
	}
	eval $body
}

After these two helper functions, it is possible to write:

set a {
	first	Fred
	last	Flintstone
	count	0
}

# define method 'greet' in dict 'a' with argument 'name'
dictMethod a greet {name} {
	puts "[dict get $this first] [dict get $this last] says hello, $name"
	dict set this count [expr [dict get $this count]+1]
	return
}

# call the method
dictCall a greet Barney

Since the method is stored inside the dict (as field method_$name), as
soon as the dict goes out of scope, the method also goes out of scope.
So it's an alternative implementation, without syntactic sugar or
apply.

- Peter

------------------------------------------------------------------------------
_______________________________________________
Tcl-Core mailing list
Tcl-...@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/tcl-core

Recent Messages in this Thread
Duquette, William H (393K) Jul 27, 2015 07:56 pm
Peter S Jul 28, 2015 12:07 pm
Duquette, William H (393K) Jul 28, 2015 03:23 pm
Cyan Ogilvie Jul 28, 2015 12:28 pm
Donal K. Fellows Jul 28, 2015 02:07 pm
Duquette, William H (393K) Jul 28, 2015 08:15 pm
Messages in this thread