Welcome back to another functional programming tidbit. Earlier I wrote about the use of the map function. The map function simply takes a function and an iterable as arguments and applies the function to each and every member of that iterable. Today we’ll be working with a new tool to add to our toolset — filter. Let’s begin! Have you ever wanted to filter out certain items within a list based on whether they followed a certain criteria? As the name suggests, the filter function does exactly that.
Imagine, again, that your boss assigns you the task of creating a food sorting web app that filters (Get it? filter…no…I’ll continue…) out the dairy products and meat products from the companies roster of various food products. You pull up your sleeves and start taking a look at a codebase that your boss provides you with.
# We manage our inventory within the inventory attribute class Company(object): def __init__(self, name,inventory): self.name = name self.inventory = inventory # Each product contains a type, category and a name class Product(object): def __init__(self,type,category,name): self.type = type self.category = category self.name = namemilk = Product(“food”,”dairy”,”milk”) cheese = Product(“food”,”diary”,”cheese”) yogurt = Product(“food”,”diary”,”yogurt”) chicken = Product(“food”,”meat”,”chicken”) steak = Product(“food”,”meat”,”steak”) wings = Product(“food”,”meat”,”wings”)# We set up a list of products here that our company ships out list_of_products = [milk,cheese,yogurt,chicken,steak,wings]# We define our company here cool_foods = Company(“Cool Foods”, list_of_products)
Your first move might be to simply create a function that takes in a product as an argument, return true or false and then evaluate the products within a loop and store the products that fit your criteria into another list. The problem with this is that you are already writing too much code. Let’s do this the “functional” way.
# First we make a "filtering" function. I call this the "BIG LIVER". It sounds good.def filter_out_diary_products(product): if product.category == “meat”: return True else: return False# The "BIG LIVER" has the job of filtering out any product that is not a meat product.filtered_products = filter(filter_out_diary_products, xyzco.inventory)
I’m glad you asked. There’s no magic here, it’s just an amazing tool. Filter takes in a function as an argument and applies, just like the map function, that function to every value of an iterable. Except this time it looks for a criteria and that criteria is whether or not the value that is passed into a particular function comes out as true. You want to evaluate values based on whether they come out false? No problem, you got filterfalse on your side. I hope you found today’s blog post quite amusing. I know you’re still baffled about the awesomeness of functional programming, but hang in there, there will be more surprises to come.