[go: up one dir, main page]

0% found this document useful (0 votes)
16 views15 pages

Unit 05

Functional programming is a paradigm that emphasizes the use of functions and is rooted in lambda calculus, allowing functions to be passed as arguments and returned from other functions. Key techniques include mapping, filtering, and reducing collections, with practical examples provided in Python. The document also discusses the integration of functional programming with object-oriented programming, highlighting the importance of understanding both approaches for effective programming.

Uploaded by

Gavi Kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views15 pages

Unit 05

Functional programming is a paradigm that emphasizes the use of functions and is rooted in lambda calculus, allowing functions to be passed as arguments and returned from other functions. Key techniques include mapping, filtering, and reducing collections, with practical examples provided in Python. The document also discusses the integration of functional programming with object-oriented programming, highlighting the importance of understanding both approaches for effective programming.

Uploaded by

Gavi Kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Functional

Programming and
GUI programming

UNIT 2
 Functional programming is a
programming paradigm in which code is
structured primarily in the form of functions.
Introducti  The origins of this programming style arise
on to from a branch of mathematics known
as lambda calculus, which is the study of
functional functions and their mathematical properties.
programm  In functional programming, you create a
ing solution by structuring code mainly using
functions.
 In functional programming, functions can be
passed in as arguments to other functions
and can be returned by other functions.
 A mapping is a one to one transformation. Each element in
the source is converted into a new value. The new values are
gathered into a collection, leaving the original collection
map, filter, unchanged. For example, suppose that you begin with the
list [1, 2, 3, 4, 5] and map using the transformation x*2+1.
and The result would be the list [3, 5, 7, 9, 11]
 A filtering is the process of testing each value in a list with a
reduce function, and retaining only those for which the function is
true. If you begin with the list [1, 2, 3, 4, 5] and filter with a
function that returns true on the odd values, the result would
be the list [1, 3, 5].
 A reduction is the process of applying a binary function to
each member of a list in a cumulative fashion. If you begin
with the list [1, 2, 3, 4, 5] and reduce using the addition
operation, the result would be ((((1 + 2) + 3) + 4) + 5), or
15.
# Example of using map, filter, and reduce in Pyth
on
data = [1, 2, 3, 4, 5]

# Using the map to apply a function to each eleme


nt
# Lambda function returns the square of x
result1 = map(lambda x: x * 2, data) # Result: [2,
4, 6, 8, 10]

# Using the filter to filter elements based on a con


dition
# Lambda function returns True for an even numbe
r
result2 = filter(lambda x: x % 2 == 0, data) # Re
sult: [2, 4]

# Using reduce to aggregate elements


# Lambda function returns product of x and y
from functools import reduce
result3 = reduce(lambda x, y: x * y, data) # Resul
t: 120
 Lambda functions,
also known as # Example of using lambda functions i
anonymous n Python
functions, can be # Lambda function that adds 1 to x
add = lambda x: x + 1
defined inline
without requiring a # Lambda function that multiplies x by
Lambda formal function
declaration and are
2
multiply = lambda x: x * 2
Functions short and one-time-
use functions. result1 = add(3) # Result: 4
result2 = multiply(3) # Result: 6
 They are helpful for
the performance of
a single task that
only requires one
line of code to
convey.
 List comprehensions are supported by Python,
which are simple and expressive techniques to
build new lists from older ones.
 Functional programming techniques such as
mapping, filtering, and aggregating can be
implemented using list comprehensions.
List # Example of using list comprehensions in Python
Comprehen data = [1, 2, 3, 4, 5]

sion # Using list comprehension to apply a function to each eleme


nt
result1 = [x * 2 for x in data] # Result: [2, 4, 6, 8, 10]

# Using list comprehension to filter elements based on a con


dition
result2 = [x for x in data if x % 2 == 0] # Result: [2, 4]

# Using list comprehension to aggregate elements


result3 = reduce(lambda x, y: x * y, data) # Result 120
 Many common tasks can be implemented as a form of
reduction. The easiest form of reduction is the sum of
the elements in a list.
>>> a = [1, 2, 3, 4, 5]
>>> print reduce(lamba x, y: x + y, a)
15
 If you want to give this a simple name you can wrap
Simple the call on reduce inside a function definition:
Reductions def sum(a):
return reduce(lambda x, y: x + y, a)
 To form the product of a list you need the three
argument form of reduce. The third argument is an
identity, the value used to begin the series of
applications. For multiplication the identity is 1.
>>> print reduce(lambda x, y: x * y, a, 1)
120
But there is much more that can be done with reduce.
Consider computing the length of a list.
Admittedly, you would probably never do it this, way, since there is a
built-in function named len for this purpose. But it’s a good exercise in
thinking about a problem as a reduction.
What is the length of an empty list? Zero, which fortunately is the
default
value. For a function you need a lambda that takes two arguments,
ignores the second,
and simply adds 1 to the first.
>>> print reduce(lambda x, y: x + 1, a)
5
How about computing the average of a list? Its simply a combination
of a sum and
dividing by the length:
def average(a):
Reductions need not be arithmetic. Imagine performing a reduction using the
function
that appends an element to the end of a list, using an empty list as the identity.
The result is a copy of a list:
>>> print reduce(lambda x, y: x + [y], a, [ ])
[1, 2, 3, 4, 5]
This might not seem particularly useful. But if we substitute another list for the
empty list as the third argument, the result is a function that appends two lists:
def append(a, b):
return reduce(lambda x, y: x + [y], b, a)
>>> print append([1, 2, 3], [5, 6, 7])
[1, 2, 3, 5, 6, 7]
Perhaps more interesting is the effect if the function appends to the front rather
than to the back. The result is a reverse of a list:
>>> print reduce(lambda x, y: [y] + x, a, [ ])
[5, 4, 3, 2, 1]
This has just scratched the surface of the types of operations that can be
performed using functional techniques. Once you start to think about how a
problem can be addressed using techniques such as mapping, filtering and
reduction you will find many other applications.
x = {"apple", "banana",
"cherry"}
y = {"google", "microsoft", OUTPUT
"apple"} {'apple'}
z = x.intersection(y)
Python Set print(z)

intersection( The intersection() method returns a set that


contains the similarity between two or more sets.
) x
Method = {"apple", "banana", "cherry
"}
y= OUTPUT
{"google", "microsoft", "apple {'apple'}
"}
z=x&y
print(z)
Use & as a shortcut instead of
intersection():
def insertionSort(arr):
n = len(arr) # Get the length of the array
if n <= 1:
return # If the array has 0 or 1 element, it is already sorted, so return
for i in range(1, n): # Iterate over the array starting from the second
element
key = arr[i] # Store the current element as the key to be inserted in
the right position
Insertion j = i-1
while j >= 0 and key < arr[j]: # Move elements greater than key one
sort position ahead
arr[j+1] = arr[j] # Shift elements to the right
j -= 1
arr[j+1] = key # Insert the key in the correct position

# Sorting the array [12, 11, 13, 5, 6] using insertionSort


arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print(arr)
quickSort(array, leftmostIndex, rightmostIndex)
if (leftmostIndex < rightmostIndex)
pivotIndex <- partition(array,leftmostIndex,
rightmostIndex)
quickSort(array, leftmostIndex, pivotIndex - 1)
quickSort(array, pivotIndex, rightmostIndex)

Quicksort partition(array, leftmostIndex, rightmostIndex)


set rightmostIndex as pivotIndex
storeIndex <- leftmostIndex - 1
for i <- leftmostIndex + 1 to rightmostIndex
if element[i] < pivotElement
swap element[i] and element[storeIndex]
storeIndex++
swap pivotElement and element[storeIndex+1]
return storeIndex + 1
 The computation of the variance of a list of numbers
illustrates how a longer function can be computed in
a series of steps that are each functional.
 A variance of a list is defined as the sum of squares of
differences of each number from the mean (average).
Computing  To compute the variance the average is first
Variance of computed. As we noted earlier, this is simply the sum
of the elements divided by the number of elements.
a List  Next, the difference of each element from the
average is computed as a mapping.
 A second mapping computes the squares. Finally, to
compute the variance the sum of the squares is
computed, and divided by the length.
def variance(a):
average = sum(a)/len(a) # compute
average
difs = map(lambda x: x – average, a)
sqs = map(lambda x: x * x, difs)
return sum(sqs)/len(a)

Notice how each step in the program is a transformation that acts on an entire
collection as a whole, without the need to write a loop. By eliminating explicit loops
the program is both shorter and easier to understand. This makes functions written
in a functional style much easier to debug and correct.
 In object-oriented programming (OOP), you structure your
code based on the concept of objects. In commonly used
OOP languages (such as Java or C#),
 we create a template for an object using the keyword class,
and we instantiate an object by using the keyword new.
 These objects contain fields that store data and methods
Combining that manipulate data. In this style, an object can be passed
as an argument in the function of another object.
Functional  It is possible to write programs entirely in a functional
and Object- fashion. However, it is more common to use functional
programming features, and combine them with other
Oriented techniques.
 An individual function might be written in a functional
Programmin fashion, while the remainder of a program is imperative.
g  object-oriented programming. It is common for a class to
include individual methods (functions) that are themselves
written in a functional fashion.
 To become a skilled Python programmer you need to learn
both the mechanics of all these techniques, as well as
being able to identify those situations in which it is
appropriate to use one approach or another.

You might also like