Functional Programming

Higher-Order Functions

Use a function as parameter. Example:

def do_twice(func,arg):
   return func(func(arg))

def double_it(arg):
   return arg * 2

print(do_twice(double_it,3))

Anonymous Functions(Lambdas)

Example:

def a_func(f, arg):
   return f(arg)

result = a_func(lambda k: k+k, 5)
print(result)

Use the

  • lambda keyword
  • the parameter variable,
  • an expression to be processed
  • a comma
  • and the value to be passed

Another example:

def add_six(x):
   return  x + 6
print(add_six(4))

print((lambda x:x + 6) (4))

Assign a Function to a Variable

Example

vat = lambda x: x * 1.19
print(vat(2))

Functions

map Function

def double_it(x):
   return x * 2

nums = [1, 2, 3, 4, 5]
res = list(map(double_it, nums))
print (res)

Alternative with an anonymous function:

nums = [1, 2, 3, 4, 5]
res = list(map(lambda x: x*2, nums))
print (res)

filter Function

Example:

nums = [1, 2, 3, 4, 5]
result = list(filter(lambda x: x%2==1, nums))
print (result)

Parameters

  • lambda variable
  • a function which returns a boolean

Generators

Example:

def counting():
   i = 0
   while i < 10:
      yield i
      i += 1

for i in counting():
   print(i)

Generators are iterables. They can be used in while and for loops.

yield defines a generator which replaces the return of a function. It does not destroy local variables

Interesting: Generators can be infinite since they don't have memory restrictions.

def nums(x):
   for i in range(x):
      if i % 3 == 0:
         yield i

print(list(nums(20)))