Created
February 28, 2015 19:22
-
-
Save Gosha/94ccc254c26b50d2af65 to your computer and use it in GitHub Desktop.
Simple example of a higher order function
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
#!/usr/bin/env python3 | |
# A classic example: | |
# create_increaser_by(num) returns a new function, the returned function adds num to it's arg | |
def create_increaser_by(num): | |
# This function is weirdly named because it's returned later on. | |
# It's not the name it will be called by | |
def _return_fun(arg): | |
return arg + num | |
# As you see, _return_fun was declared as a function and is return | |
# just like anything else | |
return _return_fun | |
# So let's try creating a function that adds 1 to anything | |
one_adder = create_increaser_by(1) | |
# one_adder is now a function that adds 1 to it's arg | |
print(one_adder(1)) # => 2 | |
print(one_adder(2)) # => 3 | |
print(one_adder(one_adder(1))) # => 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment