Last active
March 12, 2017 22:35
-
-
Save juanarrivillaga/74f7193ce1177f12e3f68ce95f5306eb to your computer and use it in GitHub Desktop.
higher order functions
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 adder(x): | |
def add_x(n): | |
return n + x | |
return add_x | |
add_1 = adder(1) | |
add_2 = adder(2) | |
add_42 = adder(42) | |
x = 10 | |
print(add_1(x)) | |
print(add_2(x)) | |
print(add_42(x)) | |
def general_poly(L): | |
exp = range(len(L) - 1, -1, -1) | |
coef = L[:] # make a copy to protect from side-effects. | |
def apply_poly(x): | |
result = 0 | |
for c, k in zip(coef, exp): | |
result += c*x**k | |
return result | |
return apply_poly | |
# even shorter way of defining apply_poly: sum(c*x**k for c, k in zip(coef, exp)) | |
def general_poly(L): | |
exp = range(len(L) - 1, -1, -1) | |
coef = L[:] # make a copy to protect from side-effects. | |
def apply_poly(x): | |
return sum(c*x**k for c, k in zip(coef, exp)) | |
return apply_poly |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment