E
Eugene Van den Bulke
Hi,
I have just finished reading Paul Graham Hackers & Painters book (which
I recommend even though he seems a bit hard on Python)
In chapter 13 of his book he wants to demonstrate LISP power VS other
languages (to be precise he wants to illustrate what he means by
relative power of programming language).
"We want to write a function that generates accumulators - a function
that takes a number n, and returns a function that takes another number
i and returns n incremented by i (that's incremented by, not plus. An
accumulator has to accumulate).
In Common Lisp this would be:
(defun foo (n)
(lambda (i) (incf n i)))
....
Python doesn't fully support lexical variables, you have to create a
data structure to hold the value of n. And although Python does have a
function data type, there is no literal representation for one (unless
the body is only a single expression) so you need to create a named
function to return. This is what you end up with:
def foo(n):
s=[n]
def bar(i):
s[0]+=i
return s[0]
return bar
"
It seems to me that this code does the job (but I am not sure I
understand exactly what an accumulator is):
def test(n):
return lambda i: n+i
Is that an accumulator? If it is, PG must have written this chapter
working on an older verion of Python ...
Regards,
Eugene Van den Bulke
I have just finished reading Paul Graham Hackers & Painters book (which
I recommend even though he seems a bit hard on Python)
In chapter 13 of his book he wants to demonstrate LISP power VS other
languages (to be precise he wants to illustrate what he means by
relative power of programming language).
"We want to write a function that generates accumulators - a function
that takes a number n, and returns a function that takes another number
i and returns n incremented by i (that's incremented by, not plus. An
accumulator has to accumulate).
In Common Lisp this would be:
(defun foo (n)
(lambda (i) (incf n i)))
....
Python doesn't fully support lexical variables, you have to create a
data structure to hold the value of n. And although Python does have a
function data type, there is no literal representation for one (unless
the body is only a single expression) so you need to create a named
function to return. This is what you end up with:
def foo(n):
s=[n]
def bar(i):
s[0]+=i
return s[0]
return bar
"
It seems to me that this code does the job (but I am not sure I
understand exactly what an accumulator is):
def test(n):
return lambda i: n+i
Is that an accumulator? If it is, PG must have written this chapter
working on an older verion of Python ...
Regards,
Eugene Van den Bulke