Posted to tcl by kbk at Sun Jul 13 19:08:32 GMT 2008view raw
- namespace path {::tcl::mathop ::tcl::unsupported}
- # Lambda is defined as constructing an invocation of [apply]
- interp alias {} lambda {} apply {args {list apply $args}}
- # The I combinator simply returns its argument
- interp alias {} I {} return -level 0
- # The U combinator passes a function as an argument to itself.
- proc U {f args} {tailcall {*}$f $f {*}$args}
- # recursive factorial
- puts [U [lambda {f x} {
- if {$x == 0} {
- I 1
- } else {
- * $x [U $f [- $x 1]]
- }
- }] 6]
- # iterative factorial
- puts [U [lambda {f y x} {
- if {$x == 0} {
- I $y
- } else {
- tailcall U $f [* $y $x] [- $x 1]
- }
- }] 1 6]