[Edu-sig] The Great Computer Language Shootout

Dustin Mitchell dustin@cs.uchicago.edu
Sun, 3 Jun 2001 13:45:53 -0500 (CDT)


On Sun, 3 Jun 2001, Luby Liao wrote:

Here's a better way to pass extra variables to a lambda, without globals:

def compose(f,g):
  return lambda x,_f=f,_g=g : _f(_g(x))

That is the closest to a lambda binding you're going to get.  Python
doesn't automatically slurp up local variables when it creates a lambda,
but it can be easily simulated using default arguments, as above.

I read about this in an article -- I think by Guido -- a while ago, but I
don't have time to look it up right now.

Enjoy.

Dustin

> How about:
> 
>   def compose(f,g):
>       global _f, _g
>       _f = f
>       _g = g
>       return lambda x: _f(_g(x))
> 
>   if __name__ == '__main__':
>       from math import *
>       print compose(sin, sqrt)(3)
>       print sin(sqrt(3))
> 
>     0.98702664499
>     0.98702664499
> 
> 
> cheers, Luby 
> 
> _______________________________________________
> Edu-sig mailing list
> Edu-sig@python.org
> http://mail.python.org/mailman/listinfo/edu-sig
> 

---------------------------------------------------------------------
| Dustin Mitchell                                        )O(        |
---------------------------------------------------------------------