summaryrefslogtreecommitdiffstats
path: root/doc/apply.n
diff options
context:
space:
mode:
Diffstat (limited to 'doc/apply.n')
-rw-r--r--doc/apply.n62
1 files changed, 45 insertions, 17 deletions
diff --git a/doc/apply.n b/doc/apply.n
index 31099ce..1e69e69 100644
--- a/doc/apply.n
+++ b/doc/apply.n
@@ -1,4 +1,7 @@
'\"
+'\" Copyright (c) 2006 Miguel Sofer
+'\" Copyright (c) 2006 Donal K. Fellows
+'\"
.so man.macros
.TH apply n "" Tcl "Tcl Built-In Commands"
.BS
@@ -8,7 +11,6 @@ apply \- Apply an anonymous function
.SH SYNOPSIS
\fBapply \fIfunc\fR ?\fIarg1 arg2 ...\fR?
.BE
-
.SH DESCRIPTION
.PP
The command \fBapply\fR applies the function \fIfunc\fR to the arguments
@@ -44,24 +46,50 @@ with '::'.
The semantics of \fBapply\fR can also be described by:
.PP
.CS
- proc apply {fun args} {
- set len [llength $fun]
- if {($len < 2) || ($len > 3)} {
- error "can't interpret \\"$fun\\" as anonymous function"
- }
- lassign $fun argList body ns
- set name ::$ns::[getGloballyUniqueName]
- set body0 {
- rename [lindex [info level 0] 0] {}
- }
- proc $name $argList ${body0}$body
- set code [catch {uplevel 1 $name $args} res opt]
- return -options $opt $res
- }
+proc apply {fun args} {
+ set len [llength $fun]
+ if {($len < 2) || ($len > 3)} {
+ error "can't interpret \\"$fun\\" as anonymous function"
+ }
+ lassign $fun argList body ns
+ set name ::$ns::[getGloballyUniqueName]
+ set body0 {
+ rename [lindex [info level 0] 0] {}
+ }
+ proc $name $argList ${body0}$body
+ set code [catch {uplevel 1 $name $args} res opt]
+ return -options $opt $res
+}
+.CE
+.SH EXAMPLES
+This shows how to make a simple general command that applies a transformation
+to each element of a list.
+.CS
+proc map {lambda list} {
+ set result {}
+ foreach $item $list {
+ lappend result [\fBapply\fR $lambda $item]
+ }
+ return $result
+}
+map {x {return [string length $x]:$x}} {a bb ccc dddd}
+ \fI=> 1:a 2:bb 3:ccc 4:dddd\fR
+map {x {expr {$x**2 + 3*$x - 2}}} {-4 -3 -2 -1 0 1 2 3 4}
+ \fI=> 2 -2 -4 -4 -2 2 8 16 26\fR
+.CE
+.PP
+The \fBapply\fR command is also useful for defining callbacks for use in the
+\fBtrace\fR command:
+.CS
+set vbl "123abc"
+trace add variable vbl write {\fBapply\fR {v1 v2 op} {
+ upvar 1 $v1 v
+ puts "updated variable to \\"$v\\""
+}}
+set vbl 123
+set vbl abc
.CE
-
.SH "SEE ALSO"
proc(n), uplevel(n)
-
.SH KEYWORDS
argument, procedure, anonymous function