Advertisement
homer512

higher order python

Nov 13th, 2014
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.30 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. """Demonstrates higher-order functions, especially functions as arguments"""
  4.  
  5.  
  6. def apply_inline(sequence, transformation, condition):
  7.     """Conditionally modifies items in a sequence
  8.  
  9.    Arguments:
  10.    sequence -- a list
  11.    transformation -- a function taking a sequence item as input and returning
  12.                      something that is supposed to replace the item in the
  13.                      sequence
  14.    condition -- a function taking a sequence item as input and returning True
  15.                 if the transformation shall be applied
  16.    """
  17.     for index, item in enumerate(sequence):
  18.         if condition(item):
  19.             sequence[index] = transformation(item)
  20.  
  21.  
  22. def transform_function(int_item):
  23.     """Just a placeholder transformation"""
  24.     return int_item + 2
  25.  
  26.  
  27. def condition_function(int_item):
  28.     """Placeholder condition that returns a True value for odd integers"""
  29.     return int_item & 1
  30.  
  31.  
  32. # Let's apply this simple stuff
  33.  
  34. sample_list = [0, 1, 2, 3, 4]
  35. apply_inline(sample_list, transform_function, condition_function)
  36. assert(sample_list == [0, 3, 2, 5, 4])
  37.  
  38.  
  39. # Now something more complicated
  40.  
  41. class TransformFunctor(object):
  42.     """Class of callable objects similar to transform_function
  43.  
  44.    Not particularly pythonesque. Just imagine something more complex
  45.    """
  46.     def __init__(self, added_value):
  47.         """Allows configuring additional transformation parameters"""
  48.         self.added_value = added_value
  49.  
  50.     def __call__(self, int_item):
  51.         """Applied like transform_function"""
  52.         return int_item + self.added_value
  53.  
  54.  
  55. def condition_factory(true_for_odd, true_for_even):
  56.     """Returns a condition_function that changes based on the arguments
  57.  
  58.    I could also return different functions depending on the arguments but this
  59.    method here also demonstrates the variable scope
  60.    """
  61.     def custom_condition(int_item):
  62.         is_odd = int_item & 1
  63.         if true_for_odd and is_odd:
  64.             return True
  65.         if true_for_even and not is_odd:
  66.             return True
  67.         return False
  68.     return custom_condition
  69.  
  70.  
  71. # And now test it
  72.  
  73. apply_inline(sample_list, TransformFunctor(added_value=1),
  74.              condition_factory(true_for_odd=False, true_for_even=True))
  75. assert(sample_list == [1, 3, 3, 5, 5])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement