On 3/25/2014 11:18 AM, Steven D'Aprano wrote:

The thing is, we can't just create a ∑ function, because it doesn't work
the way the summation operator works. The problem is that we would want
syntactic support, so we could write something like this:

     p = 2
     ∑(n, 1, 10, n**p)

Of course we can. If we do not insist on separating the dummy name from the expression that contains it. this works.

def sigma(low, high, func):
    sum = 0
    for i in range(low, high+1):
        sum += func(i)
    return sum

p = 2
print(sigma(1, 10, lambda n: n**p))
>>>
385
which looks correct. This corresponds to a notation like so

10
∑ n: n**p
1

which, for ranges, is more sensible that the standard. Lambda is an explicit rather than implicit quotation.

If you do insist on separating two things that belong together, you can quote with quote marks instead and join within the function to get the same answer.

def sig2(var, low, high, exp):
    func = eval("lambda {}: {}".format(var, exp))
    sum = 0
    for i in range(low, high+1):
        sum += func(i)
    return sum

p = 2
print(sig2('n', 1, 10, 'n**p'))
>>>
385

To me, both these apis are 'something' like the api with implicit quoting, which is impossible for function calls, but common in statements. (This is one reason to make a construct a python statement rather than function. Jumping is another) Using the same api, one could instead expand the template to include the for loop and use exec instead of eval.

def sig3(var, low, high, exp):
    loca = {}
    exec(
'''\
sum = 0
for {} in range({}, {}):
    sum += {}\
'''.format(var, low, high+1, exp), globals(), loca)

    return loca['sum']

print(sig3('n', 1, 10, 'n**p'))


This cannot be an ordinary function, because if it were, the n**p
expression would be evaluated before passing the result to the function.

So would the dummy parameter name n.

We want it to delay evaluation, like a list comp:

     [n**p for n in range(1, 11)]

the expression n**p gets evaluated inside the list comp.

Which is to say, it is implicitly quoted

That cannot be written as a function either:

     list_comp(n**p, n, range(1, 11)

It can be with explicit quoting, similar to how done for sigma. Some lisps once and maybe still have 'special' functions that implicitly quote certain arguments. One just has to learn which functions and which parameters. I prefer having implicit quoting relegated to a limited set of statements, where is it pretty clear what must be quoted for the statement to make any sense. Assignment is one example, while, for, and comprehensions are others.

--
Terry Jan Reedy


--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to