Version 7 of func

Updated 2004-06-02 19:22:41 by suchenwi

Richard Suchenwirth 2004-05-09 - Functions in Tcl are typically written with the proc command. But I notice more and more that, on my way to functional programming, my proc bodies are a single call to expr which does all the rest (often with the powerful x?y:z operator). So what about a thin abstraction around this recurring pattern?

 proc func {name argl body} {proc $name $argl [list expr $body]}

(Might have called it fun as well... it sure is.) That's all. A collateral advantage is that all expressions are braced, without me having to care. But to not make the page look so empty, here's some examples for func uses:

 func fac n     {$n<2? 1: $n*[fac [incr n -1]]}
 func gcd {u v} {$u? [gcd [expr $v%$u] $u]: $v}
 func min {a b} {$a<$b? $a: $b}
 func sgn x     {($x>0)-($x<0)} ;# courtesy rmax

Pity we have to make expr explicit again, in nested calls... But func isn't limited to math functions (which, especially when recursive, come out nice), but for expr uses in testing predicates as well:

 func atomar list          {[lindex $list 0] eq $list}
 func empty  list          {[llength $list] == 0}
 func in    {list element} {[lsearch -exact $list $element] >= 0}
 func limit {x min max}    {$x<$min? $min: $x>$max? $max: $x}

Feel free to add more meaningful examples! In any case, no one can blame me for not using return in these sweet one-liners... :)


AM (1 june 2004) I have been musing over another, related subject:

  • Define functional relations between variables (possibly defining an equation)
  • Use high-level commands to actually solve the equation

This seems an excellent way of introducing some physics into the Wiki ;)

This is the page I wrote to work out the above ideas: An equation solver


Arts and crafts of Tcl-Tk programming