Higher order  and Partial Functions

Higher order and Partial Functions

ยท

2 min read

Higher-order functions play a crucial role in functional programming paradigms. Higher-order functions like filter(), map(), and reduce() enable you to manipulate functions as first-class objects, allowing for more flexible and expressive programming.

filter()

  • The filter function selects elements from an iterable based on a given condition, returning a new iterable containing only the elements that satisfy the condition.

      # Example 2: Using filter() with lambda function
      def is_even(x):
          return x % 2 == 0
    
      numbers = [1, 2, 3, 4, 5, 6]
      even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
      print(even_numbers)  # Output: [2, 4, 6]
    

map()

  • The map function applies a given function to each element of an iterable and returns an iterable containing the results.

      def is_even(x):
          return x % 2 == 0
    
      numbers = [1, 2, 3, 4, 5, 6]
      even_numbers = list(map(lambda x: x % 2 == 0, numbers))
      print(even_numbers)  
      # Output: [False, True, False, True, False, True]
    

reduce()

  • The reduce function repeatedly applies a binary function to the elements of an iterable, reducing it to a single value by performing the specified operation cumulatively.

  • Syntax : reduce(function, list)

      import functools
    
      #Using normal function
      def sum(a, b):
          return a + b
    
      list = [2, 5, 9, 11, 13]
      val = functools.reduce(sum, list)#func takes two two element
      print(val)
    
      #Using lambda function
      list = [2, 5, 9, 11, 13]
      val = functools.reduce(lambda a, b: a+b, list)#func takes two two element
      print(val)
    

    How it works in above example of reduce()

    • Step:1 = First pass 2,5 as arguments and return 2 + 5 = 7

    • Step:2 = pass 7, 9 as arguments and return 7 + 9 = 16

    • Step:3 = pass 16, 11 arguments and return 16 + 11 = 27

    • Step:4 = pass 27 , 13 27 + 13 = 40 (Final results)

partial()

  • Partial functions in Python allow you to create new functions with fewer parameters by fixing some values from an existing function.

  • It simplifies function calls and promotes code reusability by creating specialized versions of functions with pre-filled values.

      from functools import partial
    
      def sum(a,b,c,d):
          return a+b+c+d
    
      #Passing a = 1, b = 2, c = 3
      add_portion = partial(sum,1,2,3)
    
      #Now passing d = 4
      result =  add_portion(4)
      print(result)# output = 10
    
ย