Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #54489

Re: lambda - strange behavior

Newsgroups comp.lang.python
Date 2013-09-20 09:25 -0700
References <mailman.185.1379690708.18130.python-list@python.org>
Message-ID <57ea049c-8b78-43ff-a14c-b9b4b3e5e2a4@googlegroups.com> (permalink)
Subject Re: lambda - strange behavior
From rusi <rustompmody@gmail.com>

Show all headers | View raw


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> 

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

lambda - strange behavior Kasper Guldmann <gmane@kalleguld.dk> - 2013-09-20 15:21 +0000
  Re: lambda - strange behavior Rotwang <sg552@hotmail.co.uk> - 2013-09-20 16:52 +0100
  Re: lambda - strange behavior rusi <rustompmody@gmail.com> - 2013-09-20 09:25 -0700
  Re: lambda - strange behavior Jussi Piitulainen <jpiitula@ling.helsinki.fi> - 2013-09-20 19:30 +0300

csiph-web