Functional programming in action

Programming Paradigm Concepts

Eleanor Thomas

Senior Data Analytics Engineer

Functional programming in action

  • Three examples of pure functions
  • Key difference between a pure function and a general Python function: no side effects
  • Pure functions can call other pure functions and remain pure

Drawing board

Programming Paradigm Concepts

Example 1 - Writing a pure function

def square_list(input_list):
    new_list = []

for item in input_list:
new_item = item ** 2
new_list.append(new_item)
return new_list
  • First create a new, empty list
  • Go through each item in the input list
    • Square it
    • Append it to new list
  • Return new list
Programming Paradigm Concepts

Example 2 - Correcting an "impure" function

sample_mean = 10
scale_factor = 2

def scale_list(input_list):
    new_list = []
    for item in input_list:
        new_item = (item - sample_mean) / scale_factor
        new_list.append(new_item)
    return new_list
  • Depends on variables outside of the function body
  • Not a pure function
Programming Paradigm Concepts

Example 2 - "Impure" function corrected

def scale_list(input_list, sample_mean, scale_factor):
    new_list = []
    for item in input_list:
        new_item = (item - sample_mean) / scale_factor
        new_list.append(new_item)
    return new_list
  • Variables sample_mean and scale_factor have become input parameters for the function
  • Function is now "pure"
Programming Paradigm Concepts

Example 3 - Combining pure functions

def scale_value(value, sample_mean, scale_factor):
    scaled_value = (value - sample_mean) / scale_factor
    return scaled_value

def scale_list(input_list, sample_mean, scale_factor):
    new_list = []
    for item in input_list:
        new_item = scale_value(item, sample_mean, scale_factor)
        new_list.append(new_item)
    return new_list
Programming Paradigm Concepts

Let's practice!

Programming Paradigm Concepts

Preparing Video For Download...