[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Accumulator




> 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
>         do_something_with(price)}
>     else
>        do_something_with(price)
>     end}
> end
> 
> Can you give me the equivalent python?

Well, I would *like* to be able to do it like this:

------- doesn't really work in Python
def compute_price():
 price = 0
 def handle_tax(tax):
  price += tax
  do_something_with_price(price)

 def handle_base_price(aprice):
  price = aprice
  if price > tax_threshold:
   get_tax(handle_tax)
  else:
   do_something_with_price(price)

 get_base_price(handle_base_price)
------- doesn't really work in Python

... but Python doesn't allow the use of variable `price' inside `handle_tax()' 
to mean the variable defined in `compute_price()'.  I thought that Python 2.2 
*would* do this, but it doesn't.  So what I'll do is make an object to hold
all the mutable state.  (Listing appended to this message.)

This is irritating and the next language that I intend to learn, 
E (`http://erights.org/'), does the right thing here.

But you know what?  It hardly matters at all.  If this is a victory of Lisp 
(and E) over Python, it is a tiny victory of "programming in the small".

What matters in the large is the use of the CPS idiom to avoid the problems of 
threading and locking when spreading your program's logic over multiple 
asynchronous events (like web page clicks in the case of Avi's web apps, or 
incoming messages in the case of my Mnet app).

Python does a fine job of supporting this idiom, even though I don't think the 
Python designers really appreciate it properly.  E, by the way, features this 
kind of style as a central feature of the language.  (The reason that this 
matters so much in E is that E integrates remote invocation.)

Regards,

Zooko

-------
Secure Distributed Systems Consulting -- http://zooko.com/
-------

tax_threshold = 1

def get_base_price(handler):
    handler(2)

def get_tax(handler):
    handler(3)

def do_something_with_price(price):
    print "price: ", price

class Cart:
    def __init__(self):
        self.price = None
        self.tax_threshold = 1
        
    def compute_price(self):
        def handle_tax(tax):
            self.price += tax
            do_something_with_price(self.price)

        def handle_base_price(price):
            self.price = price
            if self.price > self.tax_threshold:
                get_tax(handle_tax)
            else:
                do_something_with_price(self.price)

        get_base_price(handle_base_price)

c = Cart()
c.compute_price()