blubbafett
blubbafett

Reputation: 168

"Nested" anonymous functions/function handles in Python

Working on my Python these days, and I want to port a short Matlab code from a course I did a few years back into Python, but to be honest I can't figure out if it's possible to do it in the same manner, and if it is, how to do it.

The essential part here that I'm struggling with in Python is the following:

nk = @(x)1
for l=1:3 % calculate basis
    nk = @(x)(nk(x).*(x-1));
end

How the code works in Matlab:

nk = @(x)1 creates a function handle nk(x), which can be called by nk(xi) where e.g. xi=[1,2,3,4], but as of now it will only return 1 since it doesn't depend on the variable x, yet.

In the for-loop, nk(x) is multiplied with (x-1) for every iteration (here x is considered a "symbolic" variable, or what to call it, similar to how you define a lambda function), and in the end it should turn out as nk = (x-1)*(x-1)*(x-1).

It is still a function which I can call as nk(x), where x is an array with whatever values I want it to have.

Upvotes: 0

Views: 411

Answers (1)

John Coleman
John Coleman

Reputation: 52008

The following crude example of piecewise linear interpolation might give you an idea:

def interpolate(xs,ys):
    #assumes that xs and ys are same-length lists
    #of real numbers, with xs sorted
    def N(x):
        if x < min(xs) or x > max(xs): return False #we don't extrapolate
        if x == max(xs): return ys[-1]
        i = 0
        while xs[i] <= x:
            i+= 1
        m = (ys[i]-ys[i-1])/(xs[i]-xs[i-1])
        return ys[i-1] + m*(x - xs[i-1])
    return N

For example,

>>> f = interpolate([0,1,2],[1,2,4])
>>> f(0)
1.0
>>> f(0.7)
1.7
>>> f(1.9)
3.8
>>> f(2)
4
>>> f(2.1)
False

The key concept is that of closures. See this blog post for a nice discussion (especially the part that talks about function factories).

By the way, you can create closures with anonymous functions, though the resulting code isn't very readable:

>>> f = (lambda x: (lambda y: x+y))
>>> g = f(3)
>>> g(2)
5

Since you were mentioning function "handles", I don't think that you really want anonymous functions (especially given your original question that had more Matlab code).

Upvotes: 0

Related Questions