Skip to content

Instantly share code, notes, and snippets.

@FingerLiu
Created January 23, 2015 05:04
Show Gist options
  • Save FingerLiu/5297525b5cd0e0e5da11 to your computer and use it in GitHub Desktop.
Save FingerLiu/5297525b5cd0e0e5da11 to your computer and use it in GitHub Desktop.
use decorator to make a function elementwise.
def elementwise(fn):
def newfn(arg):
if hasattr(arg,'__getitem__'): # is a Sequence
return type(arg)(map(fn, arg))
else:
return fn(arg)
return newfn
@elementwise
def compute(x):
return x**3 - 1
print compute(5) # prints: 124
print compute([1,2,3]) # prints: [0, 7, 26]
print compute((1,2,3)) # prints: (0, 7, 26)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment