FunctionalProgramminginPython 26aug2022
FunctionalProgramminginPython 26aug2022
com Aug-2022 Pg 1 of 8
Simply put, a lambda function is just like any normal python function,
except that it has no name when defining it, and it is contained in one line
of code.
lambda argument(s): expression
A lambda function evaluates an expression for a given argument. You give
the function a value (argument) and then provide the operation
(expression). The keyword lambda must come first. A full colon (:) separates
the argument and the expression.
In the example code below, x is the argument and x+x is the expression.
#Normal python function
def a_name(x):
return x+x
#Lambda function
lambda x: x+x
argument, for example, map() and filter(). These are also called
Higher-order functions.
1. Scalar values
This is when you execute a lambda function on a single value.
(lambda x: x*2)(12)
###Results
24
In the code above, the function was created and then immediately
executed. This is an example of an immediately invoked function
expression.
2. Lists
filter(). This is a Python inbuilt library that returns only those values that
fit certain criteria. The syntax is filter(function, iterable). The iterable
can be any sequence such as a list, set, or series object (more below).
The example below filters a list for even numbers. Note that the filter
function returns a ‘Filter object’ and you need to encapsulate it with a list to
return the values.
list_1 = [1,2,3,4,5,6,7,8,9]
filter(lambda x: x%2==0, list_1)
### Results
<filter at 0xf378982348>
list(filter(lambda x: x%2==0, list_1))
###Results
[2, 4, 6, 8]
map(). This is another inbuilt python library with the syntax map(function,
iterable).
This returns a modified list where every value in the original list has been
changed based on a function. The example below cubes every number in
the list.
list_1 = [1,2,3,4,5,6,7,8,9]
Lambdas are important for map(), filter() and reduce() because the arguments that we pass to
them are often short functions needing to be used only once in our programs, so there’s no
use in saving them. Unlike regular functions that need to be defined and saved in memory,
anonymous functions are succinct and disposable.
Functional Programming is a coding style that focuses on defining what to do, instead of
performing some action. Functional programming is derived from the mathematical style of
thinking where you define the kind of inputs that go into a function and the kind of outputs that
we can expect from the function.
In functional code, the output of the function depends only on the arguments that are passed.
Calling the function f for the same value of x should return the same result f(x) no matter how
many times you pass it.
Thus, it calls for a radically different style of thinking where you are rarely changing state.
Instead of moving through steps, you think of data as undergoing transformations with the
desired result as the end state.
1. What are the characteristics of functional programming
2. How to achieve those characteristics.
3. What is the meaning of using functions as first class objects.
4. What is functional purity.
5. How to refactor procedural code to functional code.
For example, in the following example you can pass the int function as a parameter to map
function.
You can assign them to variables and return them. For example, in the following code, you
can assign the function hello_world, and then the variable will be executed as a function.
Python functional purity:
There are various built-in functions in Python that can help to avoid procedural code in
functions. So something like this
def naive_sum(list):
s = 0
for l in list:
s += l
return s
can be replaced with the following construct:
sum(list)
Similarly, built-in functions such as map, reduce, and the itertools module in Python can be
utilized to avoid side-effects in your code.
The above construct stems from the traditional thinking of visualizing the whole program as a
series of steps where you define how things need to be done. Making this more functional will
need a change in the thinking pattern. You can replace the above for loop in Python in the
following manner.
map(func, l)
This is read as “map the function to the list,” which conforms to our idea of defining the
question “what.”
If you take this idea and apply it to the sequential execution of functions, you get the following
construct.
def func1():
pass
def func2():
pass
def func3():
pass
Please note that this does not actually run the functions but returns a lazy map object. You
need to pass this object to a list or any other eager function to have the code executed.
Python Recursion:
What is Recursion
Recursion is a method of breaking a problem into subproblems which are essentially of the
same type as the original problem. You solve the base problems and then combine the
results. Usually this involves the function calling itself.
An example for recursion may be something like:
eat the dumplings: 1. check how many dumplings on the plate 2. if no dumplings left stop
eating 3. else eat one dumpling 4. "eat the dumplings"
How to implement recursion in your code
Python functions support recursion and hence you can utilize the dynamic programming
constructs in the code to optimize them. Recursion basically needs to fulfill two conditions.
There should be a condition where the recursion should end, and it should call itself for all
other conditions. The end condition should be limiting; i.e, the functions should call smaller
versions of themselves.
Example: The following code generates Fibonacci numbers through recursion.
def fib(n):
if n == 0: return 0
elif n == 1: return 1
else: return fib(n-1)+fib(n-2)
A small example showing how to convert procedural code into functional code:
Let us go through a small example where you try to refactor procedural code into functional.
In the below example, you have a starting number which gets squared, the result is
incremented by 1 and the result of that is raised to the power of 3, the code then takes the
decrement. Note that the code works in steps.
# procedural code
starting_number = 96
# define a function `call` where you provide the function and the
arguments
def call(x, f):
return f(x)
# put all the functions in a list in the order that you want to
execute them
funcs = [square, increment, cube, decrement]
https://www.hackerearth.com/practice/python/functional-programming/functional-programming
-1/tutorial/