Monday, March 17, 2014

Higher Order Functions!

Higher Order Functions

I think higher order function (functions of functions) are very cool!

For example, you can make a function that test a function with various variables and returns all the answers in a list! Look at the following example:

def square_value(value:int) -> int:
    """
    >>> square_value(5)
    25
    """
    return (value**2)

def function_tester(func:object, values:list) -> list:
    """
    >>> function_tester(square_value, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    """
    result = []
    for x in values:
        result.append(func(x))
    return result 

>>> function_tester(square_value, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Very cool! I am very curious where this can be applied and how I can use this new trick in my code! I'm sure they can help me reduce the amount of code I need to write, especially when I need to write very similar functions, or when I need to write functions that have a combination of previously defined methods.

No comments:

Post a Comment