lambda - strange behavior

rusi rustompmody at gmail.com
Fri Sep 20 12:25:08 EDT 2013


On Friday, September 20, 2013 8:51:20 PM UTC+5:30, Kasper Guldmann wrote:
> I was playing around with lambda functions, but I cannot seem to fully grasp
> them. I was running the script below in Python 2.7.5, and it doesn't do what
> I want it to. Are lambda functions really supposed to work that way. How do
> I make it work as I intend?
> 
> f = []
> for n in range(5):
>     f.append( lambda x: x*n )
> 
> assert( f[4](2) == 8 )
> assert( f[3](3) == 9 )
> assert( f[2](2) == 4 )
> assert( f[1](8) == 8 )
> assert( f[0](2) == 0 )

You are not wrong in being surprised.  Here's the python rewritten in a more functional style

And then the same in haskell.

$ python3
Python 3.3.2+ (default, Jun 13 2013, 13:47:13) 
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> fl= [lambda x: x + n for n in range(5)]
>>> [f(1) for f in fl]
[5, 5, 5, 5, 5]
>>> 

-------haskell-----
$ ghci
GHCi, version 7.4.1: http://www.haskell.org/ghc/  :? for help

Prelude> let fl = [\x-> x+n | n <- [0..4]] 
Prelude> [f 1 | f <- fl]
[1,2,3,4,5]
Prelude> 



More information about the Python-list mailing list