Created
January 23, 2015 05:04
-
-
Save FingerLiu/5297525b5cd0e0e5da11 to your computer and use it in GitHub Desktop.
use decorator to make a function elementwise.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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