Unit2-Functional - Logic Programming
Unit2-Functional - Logic Programming
School of Computing
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 calculus, Main traits are Local variables, sequence,
compositionality, formula, recursion, selection, iteration, and modularization
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
3 What it focuses is on: "What you are doing. in What it focuses is on "How you are
the programme." doing your programming."
8 Supports both "Abstraction over Data" and Supports only "Abstraction over Data".
"Abstraction over Behavior."
Features of Functional paradigms
The following command snippet shows the and operator's non-strict feature:
num = 1 num = 1
def function_to_add_one(num): def procedure_to_add_one(): global
num += 1 num
return num num += 1
function_to_add_one(num) return 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()
• The filter() method filters the given sequence with the help of a
function that tests each element in the sequence to be true or not.
• syntax:
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.
Example : # 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.
• Example3:-
Execute the code & write O/p
import functools
import operator
# 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))
print (functools.reduce(operator.add,lis))
print (functools.reduce(operator.mul,lis))
reduce() vs accumulate()
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
61
Sample Scenarios
TextBook:
1) Shalom, Elad. A Review of Programming Paradigms Throughout the History: With a Suggestion
Toward a Future Approach, Kindle Edition
2) Amit Saha, Doing Math with Python: Use Programming to Explore Algebra, Statistics,Calculus and
More, Kindle Edition, 2015
Introduction
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
–Exponentials and logarithms Reference:
–Special Functions
–Example: Continued Fractions • https://www.geeksforgeeks.org/pyth
• Calculus
–Derivatives
on-getting-started-with-sympy-mod
–Integrals ule/
–Limits
–Series Expansion • https://docs.sympy.org/latest/tutoria
–Finite differences l/index.html
• 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
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