This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

Creating a New Math Function?

Help for those learning Tcl or writing their own scripts.
Post Reply
d
dokueki
Voice
Posts: 31
Joined: Sat Apr 28, 2007 8:42 am
Location: Bat Yam, Israel
Contact:

Creating a New Math Function?

Post by dokueki »

I Googled it, but all I got was weird instructions I couldn't really understand. It'd be lovely if anyone could give me an example of how to make a new math function for expr that takes one argument, and show how to take more. Thanks in advance :)
User avatar
strikelight
Owner
Posts: 708
Joined: Mon Oct 07, 2002 10:39 am
Contact:

Post by strikelight »

Well, if you want to modify an existing command... you'd have to first rename the original command, and write a proc that is named after the command you are modifying... and within that proc scan for what you are looking for, and remember to call the renamed command for things you aren't looking for.....

eg.

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]]
  }
}
example usage:

Code: Select all

% expr sum(10)
55
% expr 5 + sum(10)
60
Hope this helps...

Edit:
After some investigating,
In more modern Tcl versions,
you can define a math function in the tcl::mathfunc namespace, making things alot easier and nicer....

eg.

Code: Select all

proc tcl::mathfunc::sum {num} { 
  set sres 0
  for {set i 1} {$i <= $num} {incr i} { 
    incr sres $i 
  }
  return $sres 
}
And you would just use it the same way as above...

Code: Select all

% expr sum(10)
55
Post Reply