2

How do I write and apply a simple lambda function using the tcl 8.6 features "apply" and "lmap"?

map (lambda x -> x*x) [list 1 2 3]

how can I write the above in Tcl 8.6? The man pages are not that self explanatory for me.

Perhaps also a more advance version, but I guess I can figure that out myself:

lambda y -> map (lambda x -> x*x) y

Basically I would like to improve this version:

proc \x {f val} {
    set res [apply $f $val]
    set res
}

set res [\x {x {expr $x*$x}} 5]
puts "res: $res"

So that I can just write:

set res [\x {expr $x*$x} 5]
puts "res: $res"
mrsteve
  • 4,082
  • 1
  • 26
  • 63

1 Answers1

3

Here's what lambda looks like:

proc lambda {arguments expression} {
    list ::apply [list $arguments [list expr $expression]]
}

Then we do this, noting that {*} is required because the inner lambda term can't be a command directly without causing other trouble that we didn't want to have in 8.5 (or 8.6):

set res [lmap x [list 1 2 3] {
    {*}[lambda x {$x * $x}] $x
}]

The 8.6 lmap is syntactically like foreach, so an extra layer of application is needed. It is, however, more easily understood by average Tcl programmers for being like that.

Note that the lambdas are fully first-class values that can be passed around however you want (put in variables, returned, stored in a list, whatever):

set square [lambda x {$x * $x}]

puts "the square of 42 is [{*}$square 42]"

(You could use λ for a command name if you wanted, but I find it awkward to type on this keyboard. I don't recommend using \x though; Tcl uses backslashes for various escaping duties.)

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215