Posted to tcl by kbk at Sun Jul 13 19:08:32 GMT 2008view raw

  1. namespace path {::tcl::mathop ::tcl::unsupported}
  2.  
  3. # Lambda is defined as constructing an invocation of [apply]
  4.  
  5. interp alias {} lambda {} apply {args {list apply $args}}
  6.  
  7. # The I combinator simply returns its argument
  8.  
  9. interp alias {} I {} return -level 0
  10.  
  11. # The U combinator passes a function as an argument to itself.
  12.  
  13. proc U {f args} {tailcall {*}$f $f {*}$args}
  14.  
  15. # recursive factorial
  16.  
  17. puts [U [lambda {f x} {
  18. if {$x == 0} {
  19. I 1
  20. } else {
  21. * $x [U $f [- $x 1]]
  22. }
  23. }] 6]
  24.  
  25. # iterative factorial
  26.  
  27. puts [U [lambda {f y x} {
  28. if {$x == 0} {
  29. I $y
  30. } else {
  31. tailcall U $f [* $y $x] [- $x 1]
  32. }
  33. }] 1 6]