Taylor's Blog

Atypical ramblings

Functional Programming

One of the more difficult concepts I’ve encountered lately is functional programming. According to Codecademy, functional programming means that “you’re allowed to pass functions around just as if they were variables or values.”

Codecademy introduces lambda to illustrate this concept.

[python]
lambda x: x % 3 == 0
[/python]is the same as

[python]
def by_three(x):
return x % 3 == 0
[/python]The function lambda creates is an anonymous function. The big question I see popping up again and again is “why use lambda?” According to this website, lambda “is often used in conjunction with typical functional concepts like filter(), map() and reduce().”

Codecademy seems to agree as all of their examples use filter. (Filter compares a list to a provided function and only returns values which are true for that function.)

[python]
my_list = range(16)
print filter(lambda x: x % 3 == 0, my_list)
# returns [0, 3, 6, 9, 12, 15]
[/python]Lambda’s are useful when you need a quick function to do some work for you. If you’re going to be using a function multiple times, you are better off using def. Here’s some more examples:

[python]
languages = [“HTML”, “JavaScript”, “Python”, “Ruby”]
print filter(lambda language: language == “Python”, languages)
#returns [‘Python’]

squares = [x**2 for x in range (1,11)]=
print filter(lambda x: x >=30 and x <= 70, squares) #returns the squares of numbers between 30 and 70: [36, 49, 64] [/python]

Updated: April 28, 2015 — 2:23 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

Taylor's Blog © 2015