Unit 4 App
Unit 4 App
                             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
                                   History
• The foundation for Functional Programming is Lambda Calculus.
  It was developed in the 1930s for the functional application,
  definition, and recursion
• LISP was the first functional programming language. McCarthy
  designed it in 1960
• In the late 70's researchers at the University of Edinburgh defined
  the ML(Meta Language)
• In the early 80's Hope language adds algebraic data types for
  recursion and equational reasoning
• In the year 2004 Innovation of Functional language 'Scala.'
•   Database processing
•   Financial modeling
•   Statistical analysis and
•   Bio-informatics
•   Haskell
•   SML
•   Clojure
•   Scala
•   Erlang
•   Clean
•   F#
•   ML/OCaml Lisp / Scheme
•   XSLT
•   SQL
•   Mathematica
                      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.
                                  Downloaded by Tushar Dineshprabhu (tushy04@gmail.com)
                                                           lOMoARcPSD|25444167
8     Supports both "Abstraction over Data" and                                  Supports only "Abstraction over Data".
      "Abstraction over Behavior."
                            Example
  Functional Programming                                              Procedural Programming
num = 1                                                               num = 1
def function_to_add_one(num):                                         def procedure_to_add_one():
   num += 1                                                              global num
   return num                                                            num += 1
function_to_add_one(num)                                                 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()
                                                                      procedure_to_add_one()
#Final Output: 2
                                                                      #Final Output: 6
                       Downloaded by Tushar Dineshprabhu (tushy04@gmail.com)
                                               lOMoARcPSD|25444167
Pure Functions:
•   Pure Functions:
•   These functions have two main properties.
    First, they always produce the same output
    for the same arguments irrespective of
    anything else.
•   Secondly, they have no side-effects i.e. they
    do modify any argument or global variables
    or output something.
                       Example
def multiply_2_pure(numbers):
  new_numbers = []
  for n in numbers:
     new_numbers.append(n * 2)
  return new_numbers
                RECURSION
•   During functional programming, there is no
    concept of for loop or while loop, instead
    recursion is used. Recursion is a process in
    which a function calls itself directly or
    indirectly
            Higher-Order
• they may be stored in data structures, passed
  as arguments, or used in control structures.
• A programming language is said to support
  first-class functions if it treats functions as
  first-class objects.
Anonymous Functions
                                Examples
Anonymous function assigned to a variable. Easy to pass around and
   invoke when needed.
const myVar = function(){console.log(‘Anonymous function here!’)}
myVar()
Anonymous function as argument
• setInterval(function(){console.log(new Date().getTime())}, 1000);
Anonymous functions within a higher order function
function mealCall(meal){
   return function(message){
   return console.log(message + “ “ + meal + ‘!!’) }
   }
const announceDinner = mealCall(‘dinner’)
const announceLunch = mealCall(‘breakfast’)
announceDinner(‘hey!, come and get your’)
announceLunch(‘Rise and shine! time for’)
                        Downloaded by Tushar Dineshprabhu (tushy04@gmail.com)
                                             lOMoARcPSD|25444167
Mathematical Background
Mathematical Background
Example :
A=5
def impure_sum(b):
   return b + A
def pure_sum(a, b):
   return a + b
print(impure_sum(6))
>> 11
print(pure_sum(4, 6))
>> 10
Example Code
Immutable variables
Other Examples
Scenario1
                            Scenario2
                                  def hof_add(increment):
                                     # Create a function that loops and adds
                                      the increment
• Imagine that we're                 def add_increment(numbers):
  tasked with creating                  new_numbers = []
  functions          that               for n in numbers:
                                           new_numbers.append(n +
  increment numbers                   increment)
  in a list by 2, 5, and                return new_numbers
  10. So instead of                  # We return the function as we do any
  creating         many               other value
                                     return add_increment
  different increment             add2=hof_add(2)
  functions, we create            print(add2([23, 88])) # [25, 90]
  1 Higher Order                  add5 = hof_add(5)
  Function:                       print(add5([23, 88])) # [28, 93]
                                  add10 = hof_add(10)
                                  print(add10([23, 88])) # [33, 98]
                        Downloaded by Tushar Dineshprabhu (tushy04@gmail.com)
                                                lOMoARcPSD|25444167
• filter(function, sequence)
   def f(x): return x%2 != 0 and x%3 ==0
   filter(f, range(2,25))
• map(function, sequence)
   – call function for each item
   – return list of return values
• reduce(function, sequence)
   – return a single value
   – call binary function on the first two items
   – then on the result and next item
   – iterate
                       Lambda Expression
# Using `def` (old way).
def old_add(a, b):
  return a + b
                           Map Function
• Takes in an iterable (ie. list), and creates a new iterable object, a
special map object.
• The new object has the first-class function applied to every element.
                                                                           values = [1, 2, 3, 4, 5]
def map(func, seq):
                                                                           add_10 = list(map(lambda x: x + 10,
  return Map(                                                                 values))
     func(x)                                                               add_20 = list(map(lambda x: x + 20,
                                                                              values))
     for x in seq
                                                                           print(add_10)
  )                                                                        >> [11, 12, 13, 14, 15]
                                                                           print(add_20)
                                                                           >> [21, 22, 23, 24, 25]
                          Filter Function
• Takes in an iterable (ie. list), and creates a new iterable object
• The new object has the first-class function applied to every element.
                                             print(odd)
                                             >> [1, 3, 5, 7, 9]
Advantages
Disadvantages
Sample Scenario
1) (The MyTriangle module) Create a module named MyTriangle that contains the
following two functions:
# Returns true if the sum of any two sides is greater than the third side.
def isValid(side1, side2, side3):
# Returns the area of the triangle.
def area(side1, side2, side3):
Write a test program that reads three sides for a triangle and computes the area if the
input is valid. Otherwise, it displays that the input is invalid.
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
Sample Scenarios
Thank you