[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Accumulator
(Zooku, I'm ccing this back to the list - hope you don't mind)
On Thu, 23 May 2002, Zooko wrote:
> In this technique, you invoke a function passing a "handler" function as one
> of the arguments. The handler later gets invoked. The handler function acts
> like a closure (as I understand it), because I typically create a new handler
> function for each invocation. e.g.:
>
> def f():
> mylist = [1,2,3] # mutable list
> myobj = SomeMarvelousClass() # object constructor -- creates new object
> def h(resultarg):
> mylist.append(resultarg)
> myobj.do_something_wonderful()
>
> f2(h) # This passes the handler func to `f2()'.
>
>Is this the kind of thing you are talking about? The idiom is absolutely
>ubiquitous in Mnet -- most classes or modules have several uses of that
>idiom.
Yes, this is precisely what I'm talking about (except in true CPS, that
happens for every function call). Just to give us a baseline, let me
express your example in Ruby:
def f
mylist = [1,2,3]
myobj = SomeMarvelousClass.new
f2() {|resultarg|
mylist << resultarg
myobj.do_something_wonderful}
end
Now, let me give you a more complex example in Ruby:
def compute_price
get_base_price() {|price|
if price > tax_threshold
get_tax(price) {|tax|
price += tax
}
end
do_something_with(price)
}
end
Can you give me the equivalent python?
You may not be used to seeing handlers nested to that degree - if I was
doing something like that, why wouldn't I write it more simply:
def compute_price
price = get_base_price()
if price > tax_threshold
price += get_tax(price)
end
do_something_with(price)
end
The answer has to do with web applications. Unless you play games with
suspending and resuming threads, it is very difficult to split a
call/return to and from a subroutine across several page views - and even
if you did use threads, it would break the minute someone hit the back
button. This is where CPS (or better yet, real continuations) come in:
unlike standard call/return semantics, it is very easy to
- hold off on returning from the method until the right web request comes in
- return from the same method multiple times, with different values
The degree to which this improves the ease and expressiveness with which
you can develop web applications is huge.
> In the bad old days I had to add ", mylist=mylist, myobj=myobj" to the
> argument list of the function `h()', but they tell me that Python 2.2 has
> removed that requirement.
Good - that was a rather ugly requirement.
Avi