Code: Select all
# rename the expr command to oexpr
rename expr oexpr
#write our new expr command
proc expr {args} {
set newargs [list]
# let's create a new function that computes the sum between 1..N
# sum(N)
foreach item $args {
if {[regexp {sum\((.*)\)} $item - num]} {
set sres 0
for {set i 1} {$i <= $num} {incr i} {
incr sres $i
}
# add our result to the new arguments that we'll call the original
# expr command with
lappend newargs $sres
} else {
# not interested in this.. just add it to the arguments to call original
# expr command with
lappend newargs $item
}
}
if {([llength $newargs] == 1) && [info exists sres]} {
# only our command was found in the expression, so just return the result
return [lindex $newargs 0]
} else {
# call the original expr command
return [oexpr [join $newargs]]
}
}
Code: Select all
% expr sum(10)
55
% expr 5 + sum(10)
60
Code: Select all
proc tcl::mathfunc::sum {num} {
set sres 0
for {set i 1} {$i <= $num} {incr i} {
incr sres $i
}
return $sres
}
Code: Select all
% expr sum(10)
55