homer512 icon

higher order python

homer512 | PRO | 11/13/14 09:54:24 PM UTC | 0 ⭐ | 613 👁️ | Never ⏰ | []
Python |

2.3 KB

|

None

|

0 👍

/

0 👎

#!/usr/bin/python
 
"""Demonstrates higher-order functions, especially functions as arguments"""
 
 
def apply_inline(sequence, transformation, condition):
    """Conditionally modifies items in a sequence
 
    Arguments:
    sequence -- a list
    transformation -- a function taking a sequence item as input and returning
                      something that is supposed to replace the item in the
                      sequence
    condition -- a function taking a sequence item as input and returning True
                 if the transformation shall be applied
    """
    for index, item in enumerate(sequence):
        if condition(item):
            sequence[index] = transformation(item)
 
 
def transform_function(int_item):
    """Just a placeholder transformation"""
    return int_item + 2
 
 
def condition_function(int_item):
    """Placeholder condition that returns a True value for odd integers"""
    return int_item & 1
 
 
# Let's apply this simple stuff
 
sample_list = [0, 1, 2, 3, 4]
apply_inline(sample_list, transform_function, condition_function)
assert(sample_list == [0, 3, 2, 5, 4])
 
 
# Now something more complicated
 
class TransformFunctor(object):
    """Class of callable objects similar to transform_function
 
    Not particularly pythonesque. Just imagine something more complex
    """
    def __init__(self, added_value):
        """Allows configuring additional transformation parameters"""
        self.added_value = added_value
 
    def __call__(self, int_item):
        """Applied like transform_function"""
        return int_item + self.added_value
 
 
def condition_factory(true_for_odd, true_for_even):
    """Returns a condition_function that changes based on the arguments
 
    I could also return different functions depending on the arguments but this
    method here also demonstrates the variable scope
    """
    def custom_condition(int_item):
        is_odd = int_item & 1
        if true_for_odd and is_odd:
            return True
        if true_for_even and not is_odd:
            return True
        return False
    return custom_condition
 
 
# And now test it
 
apply_inline(sample_list, TransformFunctor(added_value=1),
             condition_factory(true_for_odd=False, true_for_even=True))
assert(sample_list == [1, 3, 3, 5, 5])

Comments