Functional Programming in Python

 

What is Functional Programming?

Functional Programming

  • Functions are stateless
    • Functions rely only on the input rather than some global state
  • Functions have no side effects
    • For a given input a function will always produce the same output
  • Functions are first class citizens
    • Functions can be passed to functions and returned from functions

What does that mean?

bar = 0

def func(foo):
    global bar
    bar += 1
    #return value changes even
    #if the function is called 
    #with the same value multiple times
    return foo + bar

This function has side effects and is not stateless

Examples of Functional Languages

  • Haskell
  • OCaml
  • Elm

Many languages have some functional programming features

  • Newer versions of
    • Javascript
    • Python
    • C++

Python

Map, Reduce, Filter

Passing functions as arguments

Part of functional programming is being able to pass functions to functions and return functions from functions. Python is able to do this.

def func(foo, bar):
  return foo(bar)

def plusone(x):
  return x+1

print(func(plusone,5))
#output: 6

Lambda functions!

Sometimes its a pain to make a whole separate function. Lambda functions let you make a function with no name that you can use or pass into a function.

def func(foo, bar):
  return foo(bar)

print(func(lambda x: x+1,5))
#output: 6
#same as previous example
#but less code

Map

Map takes a function and a list and applies the function to each element of the list.

def func(foo, bar):
  return list(map(foo,bar))

def plusone(x):
  return x+1

print(func(plusone,[1,6,8,15]))
#output: [2, 7, 9, 16]

Map problem:

Note: the only line in the function should be the return statement

 

Create a function that takes a list of numbers and returns 2* the value for each value if the value is > 0.

def func(foo):
  return list(map(lambda x: x*2 if x > 0 else x, foo))

print(func([-2,5,-3,8,1]))

Filter

Filter takes a function and a list and only keeps elements that the function returns true for

def func(foo):
  return list(filter(lambda x: x > 0, foo))

print(func([-2,5,-3,8,1]))

Filter problem:

Create a function that takes a list and a value and removes all of the elements that are divisible by the value.

Haskell

Whats Haskell?

  • Pure functional language
  • Features
    • Lazy evaluation
    • Pattern matching
    • Statically typed

Quick example

fib :: [Integer] -> [Integer]
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

  fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

FP Python

By theasocialmatzah

FP Python

  • 236