Unit2-Functional - Logic Programming
Unit2-Functional - Logic Programming
School of Computing
Presented by,
Mrs.S.Amudha
Paradigm types
Unit IV
– Functional Programming Paradigm [Text Book :1]
– Logic Programming Paradigm [Text Book : 1& 3]
– Dependent Type Programming Paradigm
– Network Programming Paradigm [ Text Book :4]
Text Book:
Definition
• Mainly treat computation to evaluate mathematical Functions
• Avoids changing-state and mutable data
• Called as declarative programming paradigm
• Output depends on argument passing
• Calling same function several times with same values produces
same result
• Uses expressions or declarations rather than statements as in
imperative languages
Concepts
• Database processing
• Financial modeling
• Statistical analysis and
• Bio-informatics
Functional Programming Languages
• Haskell
• SML
• Clojure
• Scala
• Erlang
• Clean
• F#
• ML/OCaml Lisp / Scheme
• XSLT
• SQL
• Mathematica
Basic Functional Programming Terminology and Concepts
Functional Vs Procedural
S.No Functional Paradigms Procedural Paradigm
2 Main traits are Lambda Main traits are Local variables, sequence,
calculus, compositionality, formula, recursio selection, iteration, and modularization
n, referential transparency
3 Functional programming focuses Procedural programming focuses
on expressions on statements
4 Often recursive. Always returns the same The output of a routine does not always
output for a given input. have a direct correlation with the input.
6 Must be stateless. i.e. No operation can have Execution of a routine may have side
side effects. effects.
7 Good fit for parallel execution, Tends to Tends to emphasize implementing
emphasize a divide and conquer approach. solutions in a linear fashion.
Functional Vs Object-oriented Programming
S.No Functional Paradigms Object Oriented Paradigm
8 Supports both "Abstraction over Data" and Supports only "Abstraction over Data".
"Abstraction over Behavior."
Functional Programming in Python
num = 1 num = 1
def function_to_add_one(num): def procedure_to_add_one():
num += 1 global num
return num num += 1
return num
function_to_add_one(num)
procedure_to_add_one()
function_to_add_one(num)
procedure_to_add_one()
function_to_add_one(num) procedure_to_add_one()
function_to_add_one(num) procedure_to_add_one()
function_to_add_one(num) procedure_to_add_one()
filter(function, sequence)
• Parameters:
• function: function that tests if each element of a sequence
true or not.
• sequence: sequence which needs to be filtered, it can
be sets, lists, tuples, or containers of any iterators.
• Returns:
returns an iterator that is already filtered.
Example1
Application:
• It is normally used with Lambda functions to
separate list, tuple, or sets.
Print vowels using filter
alphabets = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
• # function that filters vowels
def filterVowels(alphabet):
vowels = ['a', 'e', 'i', 'o', 'u']
if(alphabet in vowels):
return True
else:
return False
filteredVowels = filter(filterVowels, alphabets)
print('The filtered vowels are:')
for vowel in filteredVowels:
print(vowel)
Example: Filter the array, and return a new array with
only the values equal to or above 18
2. Python map()
Syntax :
map(fun, iter)
Python program to demonstrate working
# of map.
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
---------------------------------------------------------------------------------
O/p - {2, 4, 6, 8}
• CODE 2
We can also use lambda expressions with map
to achieve above result.
#Double all numbers using map and lambda
numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)
print(list(result))
O/p - {2, 4, 6, 8}
# Add two lists using map and lambda
numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]
result = map(lambda x, y: x + y, numbers1,
numbers2)
print(list(result))
Output :
[5, 7, 9]
Map
# List of strings
#Python map() function with multiple
arguments
• Take a look at the example of using map() function
with multiple iterable arguments.
• We have defined one list and iterator and passed
that to the map function, and it will return the
multiplication of that list and tuple and returns the
iterator, and we have converted that iterator to the
list.
Map with List and tuples
Return Value from map()
• The map() function applies a given to function
to each item of an iterable and returns a list of
the results.
Working :
• At first step, first two elements of sequence are picked and the
result is obtained.
• Next step is to apply the same function to the previously
attained result and the number just succeeding the second
element and the result is again stored.
• This process continues till no more elements are left in the
container.
• The final returned result is returned and printed on console.
# python code to demonstrate working of reduce()
# importing functools for reduce()
import functools
# initializing list
lis = [ 1 , 3, 5, 6, 2, ]
# using reduce to compute sum of list
print ("The sum of the list elements is : ",end="")
print (functools.reduce(lambda a,b : a+b,lis))
# using reduce to compute maximum element from list
print ("The maximum element of the list is : ",end="")
print (functools.reduce(lambda a,b : a if a > b else b,lis))
Output:
The sum of the list elements is : 17
The maximum element of the list is : 6
Using Operator Functions
• reduce() can also be combined with operator
functions to achieve the similar functionality as
with lambda functions and makes the code more
readable.
reduce() vs accumulate()
• Both reduce() and accumulate() can be used to calculate
the summation of a sequence elements. But there are
differences in the implementation aspects in both of these.
innerFunction()
if __name__ == '__main__':
outerFunction('Hey!')
• As we can see innerFunction() can easily be accessed inside the
outerFunction body but not outside of it’s body. Hence, here,
innerFunction() is treated as nested Function which uses text as
non-local variable.
Python Closures
def innerFunction():
print(text)
if __name__ == '__main__':
myFunction = outerFunction('Hey!')
myFunction()
O/p -Hey
When and why to use Closures:
2) A prime number is called a Mersenne prime if it can be written in the form for some
positive integer p. Write a program that finds all Mersenne primes with and displays the
output as follows:
p 2^p - 1
2 3
3 7
5 31
62
Sample Scenarios
TextBook:
predicates
animal(being) % all animals are beings
dog(being) % all dogs are beings
die(being) % all beings die
clauses
animal(X) :- dog(X) % all dogs are animals
dog(fido). % fido is a dog
die(X) :- animal(X) % all animals die
SymPy Overview
• Simplification
– simplify
– Polynomial/Rational Function
Simplification
– Trigonometric Simplification
– Powers Reference:
– Exponentials and logarithms
– Special Functions • https://www.geeksforgeeks.org/pyth
– Example: Continued Fractions on-getting-started-with-sympy-
• Calculus
– Derivatives module/
– Integrals
– Limits
• https://docs.sympy.org/latest/tutoria
– Series Expansion l/index.html
– Finite differences
• Solvers
– A Note about Equations
– Solving Equations Algebraically
– Solving Differential Equations
• Matrices
– Basic Operations
– Basic Methods
– Matrix Constructors
– Advanced Methods
– Possible Issues
Scenario Questions
TextBook:
1) Amit Saha, Doing Math with Python: Use Programming to Explore Algebra,
Statistics,Calculus and More, Kindle Edition, 2015
URL :
• https://tech.peoplefund.co.kr/2018/11/28/programming-paradigm-and-python-
eng.html
• https://freecontent.manning.com/a-first-example-of-dependent-data-types/
Introductions
• Dependent functions
– The return type of a dependent function may depend on
the value (not just type) of one of its arguments
• Dependent pairs
– A dependent pair may have a second value of which the
type depends on the first value
Network Programming Paradigm
Unit-IV (15 Session)
Session 11-15 cover the following topics:-
– Network Programming Paradigm - S11-SLO1
– Socket Programming: TCP & UDP Connection oriented, connectionless – S11-SLO2
– Sock_Stream, Sock_Dgram, socket(),bind(), recvfrom(), sendto(), listen()– S12-SLO 1
– Server-Client; send(), recv(), connect(),accept(), read(), write(), close()– S12-SLO 2
– Other languages: PowerShell, Bash, TCL S13-SLO 1
– Demo: Socket Programming in Python S13-SLO2
TextBook:
• sock_object.connect():
– This method is used to connect the client to host and port
– Initiate the connection towards the server.
General Socket Methods
• sock_object.recv():
– Use this method to receive messages at endpoints when the value of the protocol
parameter is TCP.
• sock_object.send():
– Apply this method to send messages from endpoints in case the protocol is TCP.
• sock_object.recvfrom():
– Call this method to receive messages at endpoints if the protocol used is UDP.
• sock_object.sendto():
– Invoke this method to send messages from endpoints if the protocol parameter is
UDP.
• sock_object.gethostname():
– This method returns hostname.
• sock_object.close():
– This method is used to close the socket. The remote endpoint will not receive
data from this side.
Python Socket Programming WorkFlow
Reference
• [T1] Elad Shalom, A Review of Programming Paradigms throughout the
History: With a suggestion Toward a Future
Approach, Kindle Edition, 2018
• https://www.dataquest.io/blog/introduction-functional-programming-python/
• https://tech.peoplefund.co.kr/2018/11/28/programming-paradigm-and-python-
eng.html
• https://freecontent.manning.com/a-first-example-of-dependent-data-
types/
• https://www.guru99.com/functional-programming-tutorial.html#1
Thank you