Post details: lambda curry

09/13/06

Permalink 09:47:21 pm, Categories: Python, 277 words   English (US)

lambda curry

Curry functions are best described as cocked functions. You can do this with lambda, and it's really useful for callbacks where you'd like to add some extra data not normally given to the callback.

Let's say you have some library function that looks like:

def Foo(command, callback):
  ...

Foo takes a command, executes it, then calls callback with the status when it's finished, i.e.:

  callback(status)

Normally you'd have your own method that would be the callback and take one status argument. However, what if you'd like more information passed to your callback than just status? Let's say you want the callback to get the command as an argument as well. That's where lambda comes in. Let's say your callback looks like:

def MyCallback(command, status):
  ...

Then you would just do:

command = 'blah'
fn = lambda status: MyCallback(command, status)
Foo(command, fn)

Now MyCallback will be called with both the command and the status. The power of lambda!

Update: This is absolutely wrong. Check out this example:

>>> def foo(n, x, y):
...   return x + y + n
...
>>> num=5
>>> f = lambda x,y: foo(num, x, y)
>>> num=10
>>> f(6, 7)
23

The lambda still refers to the num variable, not its value at lambda creation. What if I want to use the value 5 above for num and not 10? That's when a curry is absolutely needed. PEP 309 explains it. Generally you can create a curry method to do this:

def curry(fn, *cargs, **ckwargs):
  def call_fn(*fargs, **fkwargs):
    d = ckwargs.copy()
    d.update(fkwargs)
    return fn(*(cargs + fargs), **d)
  return call_fn

Then for the above example I would do:

>>> num=5
>>> f = curry(foo, num)
>>> num=10
>>> f(6, 7)
18

Ah, much better!

Comments, Pingbacks:

No Comments/Pingbacks for this post yet...

Leave a comment:


Warning: touch() [function.touch]: Unable to create file /hsphere/local/home/valankar/viraj.org/_tmp/hn_captcha_counter.txt because No such file or directory in /hsphere/local/home/valankar/viraj.org/b2evolution/blogs/skins/hn_captcha.class.x1.php on line 209

Warning: touch() [function.touch]: Unable to create file /hsphere/local/home/valankar/viraj.org/_tmp/hn_captcha_counter.txt because No such file or directory in /hsphere/local/home/valankar/viraj.org/b2evolution/blogs/skins/hn_captcha.class.x1.php on line 209


An ERROR has occured!
Here you might send email-notification to webmaster or something like that.

Unable to safe captcha-image.