From: "Mauricio Fernández" Date: 2003-03-27T04:40:40+09:00 Subject: Re: What are the differences between Ruby's blocks and Python's lambdas? On Thu, Mar 27, 2003 at 02:20:48AM +0900, Paul Brannan wrote: > On Thu, Mar 27, 2003 at 01:01:25AM +0900, Mauricio Fern�ndez wrote: > > For the record: > > > > There's one thing Ruby's closures do and Python's cannot, as described in > > [ruby-talk:67618]. Doesn't seem to make a difference in praxis and there > > is a workaround to solve that, though. > > This isn't entirely true. I can write the following ruby code: Don't know Python, was just copying something I thought was agreed on :) > make_counter = proc { |start| > proc { |inc| start += inc } > } > > counter = make_counter[0] > p counter[3] # ==> 3 > p counter[2] # ==> 5 > > and the following Python code would be equivalent: > > def make_counter(start): > l = lambda inc, v=vars(): ( > v.update({'start' : v['start'] + inc}), v['start'])[1] > return l > > counter = make_counter(0) > print counter(3) > print counter(2) > > I really don't know Python very well, so there's probably a much better > way to write this. The idea, though is that all local vars are stored > in a dict; that dict is accessible using the vars() function. I can > store that dict for use later (and thus retain access to all the local > variables, as in a real closure) by using default arguments to the lambda. Do you know if any optimization is done on access to outer scope locals? That looks nice but apparently slow (construction of a dict, copying table of locals...) > In Python's defense, Python lambdas are callable the same way that > functions are called. Ruby requires special syntax (either f[] or > f.call()) to call a lambda. This is only a minor nuisance in practice, > since it's always possible to create a Method object that is callable > the same way that a lambda is called. I don't understand what you mean by the last sentence batsman@tux-chan:~$ ruby -e "p Method.instance_methods.sort" ["[]", "arity", "call", "clone", "inspect", "to_proc", "to_s", "unbind"] how do I call a Method object the same way as a lambda? -- _ _ | |__ __ _| |_ ___ _ __ ___ __ _ _ __ | '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ | |_) | (_| | |_\__ \ | | | | | (_| | | | | |_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_| Running Debian GNU/Linux Sid (unstable) batsman dot geo at yahoo dot com <|ryan|> I don't use deb u poor man netgod: heh apt-get install task-p0rn