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 + barThis function has side effects and is not stateless
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: 6Sometimes 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 codeMap 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]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 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]))Create a function that takes a list and a value and removes all of the elements that are divisible by the value.
fib :: [Integer] -> [Integer]
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)fibs = 0 : 1 : zipWith (+) fibs (tail fibs)