Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Unt 5-Functional Programming

Uploaded by

tejuabhang05
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unt 5-Functional Programming

Uploaded by

tejuabhang05
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 74

Unit 5

FUNCTIONAL
PROGRAMMING
Functional Programming
● Functional programming languages are specially designed to
handle symbolic computation and list processing
applications.
● Based on mathematical functions
● Some of the popular functional programming languages
include: Lisp, Python, Erlang, Haskell, Clojure, javascript
etc.
Functional Programming
Divided into 2 Groups

1) Pure Functional Language - Support Only Functional Paradigm


Eg. Haskell
2) Impure Functional Language - Support Functional as well as
Imperative Eg. LISP
The most prominent characteristics of functional programming are as follows −

● Functional programming languages are designed on the concept of


mathematical functions that use conditional expressions and recursion
to perform computation.
● Functional programming supports higher-order functions and lazy
evaluation features.
● Functional programming languages don’t support flow Controls like loop
statements and conditional statements like If-Else and Switch
Statements. They directly use the functions and functional calls.
● Like OOP, functional programming languages support popular concepts
such as Abstraction, Encapsulation, Inheritance, and Polymorphism.

First Class Functions means
A Programming language is considered to have First-Class
functions support when it has no restrictions/limits on
how functions can be created or used.
● It includes any data structures, functions can return
another function, functions can pass any parameters etc.

Side Effect Means


● if function modifies some state variable value(s) outside its
local environment, which has effect on its invoking function.
● Example side effects include modifying a
non-local variable, a static local variable, a mutable
argument passed by reference, performing I/O or calling
other functions
High Order Functions
Lazy Evaluation
● Lazy evaluation is used in Unix map functions to improve their
performance by loading only required pages from the disk.
No memory will be allocated for the remaining pages.
● It allows the language runtime to discard sub-expressions that
are not directly linked to the final result of the expression.
● It reduces the time complexity of an algorithm by
discarding the temporary computations and conditionals.
● It is best suited for loading data which will be infrequently
accessed.
There are two methods to evaluate an expression.
1. Strict
2. Lazy

The strict means, evaluate the expression now and the lazy means, evaluate it for the first
use.

Example of VARIABLE Assignment

1.Strict evaluation
val s = factorial(15) / factorial(11)
println(s)

2.Lazy evaluation
lazy val l = factorial(15) / factorial(11)
println(l)
Functional Programming OOP

Uses Immutable data. Uses Mutable data.

Follows Declarative Programming Model. Follows Imperative Programming Model.

Focus is on: “What you are doing” Focus is on “How you are doing”

Supports Parallel Programming Not suitable for Parallel Programming

Functional Programming vs. Its methods can produce serious side effects.
Its functions have no-side effects
Object-oriented Programming
Flow Control is done using function calls & Flow control is done using loops and
function calls with recursion conditional statements.

It uses "Loop" concept to iterate Collection


It uses "Recursion" concept to iterate Collection
Data. For example: For-each loop in Java
Data.

Execution order of statements is not so Execution order of statements is very


important. important.

Supports both "Abstraction over Data" and


Supports only "Abstraction over Data".
"Abstraction over Behavior".
GNU EMACS
LISP IS USED BY

London Tube : resource


planning, allocation, and
management in the
transportation sector.

Uses Racket …Common


Aircraft design development and Uses AutoLISP LISP
analysis.
Understanding symbol manipulation
● In computer programming, symbolic programming is a
programming paradigm in which the program can manipulate
its own formulas and program components as if they were
plain data.
● Through symbolic programming, complex processes can be
developed that build other more intricate processes by
combining smaller units of logic or functionality.
● Thus, such programs can effectively modify themselves and
appear to "learn", which makes them better suited for
applications such as artificial intelligence, expert systems,
natural language processing, and computer games.
Understanding symbol manipulation
● In LISP, the fundamental things formed from bits are word-
like objects called atoms.
● Groups of atoms form lists. Lists themselves can be grouped
together to form higher-level lists. Indeed, the ability to
form hierarchical groups is of fundamental importance.
● Atoms and lists collectively are called symbolic
expressions. Working with them is what symbol
manipulation using LISP is about.
● Indeed,Symbol manipulation is sometimes called LIST
Processing.
The relationships between various
types of objects
EXAMPLE 1
(RULE IDENTIFY
(IF (ANIMAL HAS POINTED TEETH)
(ANIMAL HAS CLAWS)
(ANIMAL HAS FORWARD EYES))
(THEN (ANIMAL IS CARNIVORE)))
Basic LISP functions
Square Root
Subtract

Multiply 2 to the Power 3

Quotient
-(8)

MAximum
-(-8)

Minimum

Absolute
Add 1

Subtract 1
More LISP functions

● CAR - Access First ELement of List

● CDR - Returns Remaining Elements excluding First element of a List

● APPEND - It merges two or more list into one.

● CONS - It takes two arguments, an element and a list and returns a

list with the element inserted at the first place.


CAR and CDR Operation of LISP
LISP Handles Both Fixed and Floating
Numbers
● Fixed-point numbers are used to represent integers,
● Floating-point numbers are used to represent reals.
● FLOAT converts fixed-point numbers into floating-point ones
● FIX producing the largest integer that is less than or equal to
its argument.
CAR and CDR Operation of LISP
(CAR '((A B) C)) (CDR '((A B) C))

(A B) (C)

Also note that when CDR is applied to a list with only one element,
it returns the empty list, sometimes denoted by 0.
CAR and CDR Operation of LISP
● CAR and CDR operations can be nested together
● (CAR (CDR (A B C))
● How far should the evaluation process go into an s-
expression?
● The user specifies where to stop evaluation by supplying an

evaluation-inhibiting signal in the form of a quote character, '


● (CAR (CDR '(A B C))) -------> B
● Moving the quote mark changes the result

● (CAR ' (CDR (A B C))) --------------> (CDR (A B C)


Evaluate Following S Expression
● (CAR '(P H W))

● (CDR '(B K P H))

● (CAR '((A B) (C D)))

● (CDR '((A B) (C D)))

● (CAR (CDR '((A B) (C D))))

● (CDR (CAR '((A B) (C D))))

● (CDR (CAR (CDR '((A B) (C D)))))

● (CAR (CDR (CAR '((A B) (C D)))))


Evaluate Following S Expression
● (CAR '(P H W)) ………. P

● (CDR '(B K P H)) …………. K P H

● (CAR '((A B) (C D))) ……… (A B)

● (CDR '((A B) (C D))) ……….. (C D)

● (CAR (CDR '((A B) (C D)))) ……..C

● (CDR (CAR '((A B) (C D)))) ………B

● (CDR (CAR (CDR '((A B) (C D))))) ………….NIL

● (CAR (CDR (CAR '((A B) (C D))))) ………B


APPEND, LIST, and CONS Construct Lists

APPEND strings together the elements of all lists supplied as arguments:


● (SET 'L '(A B))
APPEND
○ (A B)
● (APPEND L L)
○ (A B A B)
● (APPEND L L L)
○ (A B A B A B)
● (APPEND '(A) '() '(B) '())
○ (A B)
● (APPEND 'L L)
○ ERROR
● (APPEND '((A) (B)) '((C) (D)))
○ ((A) (B) (C) (D))
LIST
LIST does not run things together like APPEND does. Instead, it makes a
list out of its arguments. Each argument becomes an element of the new
list.
● (LIST L L)
○ ((A B) (A B))
● (LIST L L L)
○ ((A B) (A B) (A B))
● (LIST 'L L)
○ (L (A B))
● (LIST '((A) (B)) '((C) (D)))
○ (((A) (B)) ((C) (D)))
CONS
CONS takes a list and inserts a new first element. CONS is a mnemonic
for list constructor.
● (CONS <new first element) <some list))
● (CAR (CONS 'A '(B C)))
○ A
● (CDR (CONS 'A '(B C)))
○ (B C)
● L
○ (A B)
● (CONS (CAR L) (CDR L))
○ (A B)
APPEND, LIST, and CONS Construct Lists
LENGTH, REVERSE, SUBST, and LAST
● LENGTH counts the number of elements in a list.

● REVERSE turns a list around.

● Both consider what they get to be a list of elements, not

caring whether the elements are atoms or lists.

● Often they are used on lists that have lists as elements, but

they do nothing with the insides of those elements.


LENGTH, REVERSE
Assume, in the following examples, that the value of L is still (A B).

● (REVERSE '(A B))


● (LENGTH '(A B))
○ (B A)
○ 2
● (REVERSE '((A B) (C D)))
● (LENGTH '((A B) (C D)))
○ ((C D) (A B))
○ 2
● (REVERSE L)
● (LENGTH L)
○ (B A)
○ 2
● (REVERSE (APPEND L L))
● (LENGTH (APPEND L L))
○ (B A B A)
○ 4
SUBST
● SUBST takes three arguments, one of which is an s-expression
in which occurences of a specified s-expression are to be
replaced.
● The first argument is the new s-expression to be substituted
in;
● The second is the s-expression to be substituted for;
● The third is the s-expression to work on:
● (SUBST <new s-expression> <old s-expression> (s-
expression to work on>)
SUBST
Assume, in the following examples, that the value of L is still (A B).

● (SUBST 'A 'B '(A B C))


○ (A A C)
● (SUBST 'B 'A '(A B C))
○ (B B C)
● (SUBST 'A 'X (SUBST 'B 'Y '(SQRT (PLUS (TIMES X X) (TIMES Y Y)))))
○ (SQRT (PLUS (TIMES A A) (TIMES B B)))
LAST
● LAST returns a list which contains only the last element of
the list given as the argument:
● (LAST '(A B C))
○ (C)
● (LAST '((A B) (C D)))
○ ((C D))
● (LAST 'A)
○ ERROR
Evaluate the following s-expressions:
● (LENGTH '(PLATO SOCRATES ARISTOTLE))
● (LENGTH '((PLATO) (SOCRATES) (ARISTOTLE)))
● (LENGTH '((PLATO SOCRATES ARISTOTLE)))
● (REVERSE '(PLATO SOCRATES ARISTOTLE))
● (REVERSE '((PLATO) (SOCRATES) (ARISTOTLE)))
● (REVERSE '((PLATO SOCRATES ARISTOTLE)))
Basic Building Blocks in LISP

LISP programs are made up of three


basic building blocks −
● Atom
● List
● String
● An atom is a number or string of
contiguous characters. It includes numbers
and special characters. Following are
examples of some valid atoms −hello-from-
tutorials-point
-name
-123008907
-*hello*
-Block#221
-abc123
● A list is a sequence of atoms and/or other lists enclosed in parentheses.
● Following are examples of some valid lists −
( i am a list)
(a ( a b c) d e fgh)
(father tom ( susan bill joe))
(sun mon tue wed thur fri sat)
A string is a group of characters enclosed in double
quotation marks.
Following are examples of some valid strings −
" I am a string"
"a ba c d efg #$%^&!"
"Please enter the following
details :"
"Hello from 'Tutorials Point'! "
Basic LISP Definitions
Procedure, Function, and Program
● A procedure is a recipe for action.
● A function is a kind of procedure for which it is convenient to think in
terms of an output called the value and inputs called the
arguments.
● Mathematical procedures, in particular, are often called functions.
● A program is an embodiment of a procedure in a
particular programming language.
Syntax
(DEFUN <function name>
(<parameter 1> <parameter 2> ... <parameter n)
<process description>)

(DEFUN F-TO-C (TEMP)


(QUOTIENT (DIFFERENCE TEMP 32) 1.8))
F-TO-C
Example
● SUPER-HOT is 100.
● (F-TO-C SUPER-HOT)
● (QUOTIENT (DIFFERENCE 100 32) 1.8)
● The value returned is 37.77
Example
● (DEFUN INCREASE (X Y) //definition
● (QUOTIENT (TIMES 100.0 (DIFFERENCE Y X)) X)) ;
//Nested operations.
● INCREASE
● (INCREASE 10.0 15.0) //call
● 50.0 //output
Predicate
●A Predicate Is a Function that Returns T or NIL
●T and NIL correspond to logical true and false.
●The values are preset, the value of T is T and the value of
NIL is NIL.

●(equal (+ 2 2 ) 4)
●output: T
●Some of the Predicates are : ATOM, BOUNDP, EQUAL, NULL,
NUMBERP, GREATERP and LESSP, ZEROP AND, OR, and NOT are
used to do Logic
Predicate
Sr.No. Predicate & Description

1
atom - It takes one argument and returns t if the argument is an atom or nil if otherwise.

2 equal - It takes two arguments and returns t if they are structurally equal or nil otherwise.

3 eq - It takes two arguments and returns t if they are same identical objects, sharing the same memory location or
nil otherwise.

4 eql - It takes two arguments and returns t if the arguments are eq, or if they are numbers of the same type with the
same value, or if they are character objects that represent the same character, or nil otherwise

5 evenp - It takes one numeric argument and returns t if the argument is even number or nil if otherwise.

6 oddp - It takes one numeric argument and returns t if the argument is odd number or nil if otherwise

7 zerop - It takes one numeric argument and returns t if the argument is zero or nil if otherwise.

8 null - It takes one argument and returns t if the argument evaluates to nil, otherwise it returns nil.
ATOM
● ATOM is a predicate that tests its argument to see
if it is an atom.
● let us make the value of the atom DIGITS be a list of
the names of the numbers from zero to nine:
● (SETQ DIGITS '(ZERO ONE TWO THREE FOUR FIVE
SIX SEVEN EIGHT NINE))
ATOM
● (ATOM 'DIGITS)
○ T means
True
● (ATOM 'FIVE)
○ T
● (ATOM DIGITS)
○ NIL
● (ATOM '(ZERO ONE TWO THREE FOUR FIVE SIX SEVEN
EIGHT NINE))

BOUNDP
● BOUNDP expects a symbolic atom as its argument. It
tests if its argument has a value.
● If it does, it returns T. Otherwise it returns NIL.
● (BOUNDP 'DIGITS)
○ T
● (BOUNDP 'ZERO)
○ NIL
● (BOUNDP (CAR DIGITS))
○ NIL
EQUAL
● EQUAL is another fundamental predicate. It takes two
arguments and returns T if they are the same.
Otherwise it returns NIL:
● (EQUAL DIGITS DIGITS)
○ T
● (EQUAL 'DIGITS 'DIGITS)
○ T
● (EQUAL DIGITS '(ZERO ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE))
○ T
● (EQUAL DIGITS 'DIGITS)
○ NIL
NULL
● NULL checks to see if its argument is an empty list:
● (NULL '())
○ T
● (NULL T)
○ NIL
● (NULL DIGITS)
○ NIL
● (NULL 'DIGITS)
○ NIL
NUMBERP
● NUMBERP tests its argument to see if it is a number:
● (NUMBERP 3.14)
○ T
● (NUMBERP FIVE)
○ T
● (NUMBERP 'FIVE)
○ NIL
● (NUMBERP DIGITS)
○ NIL
● (NUMBERP 'DIGITS)
○ NIL
GREATERP and LESSP
● GREATERP and LESSP expect their arguments to be
numbers.
● GREATERP tests them to see that they are in strictly
descending order.
● LESSP checks to see that they are in strictly ascending
order.
● Both may be given any number of arguments.
GREATERP and LESSP
● (GREATERP FIVE 2)
○ T
● (GREATERP 2 FIVE)
○ NIL
● (LESSP 2 FIVE)
○ T
● (LESSP FIVE 2)
○ NIL
● (LESSP 2 2)
○ NIL
GREATERP and LESSP
● (GREATERP FIVE FOUR THREE TWO ONE)
○ T
● (GREATERP THREE ONE FOUR)
○ NIL
● (GREATERP 3 1 4)
○ NIL
ZEROP
● ZEROP expects a number. It tests its argument to see if it is
zero:
● (ZEROP ZERO)
○ T
● (ZEROP 'ZERO)
○ ERROR
● (ZEROP FIVE)
○ NIL
MINUSP
● MINUSP tests whether a number is negative:
● (MINUSP ONE)
○ NIL
● (MINUSP (MINUS ONE))
○ T
● (MINUSP ZERO)
○ NIL
NOT
● NOT returns T only if its argument is NIL.
● (NOT NIL)
○ T
● (NOT T)
○ NIL
● (NOT 'DOG)
○ NIL
● (SETQ PETS '(DOG CAT))
○ (DOG CAT)
● (NOT (MEMBER 'DOG PETS))
○ NIL
● (NOT (MEMBER 'TIGER PETS))
○ T
AND, OR and NOT
AND, OR and NOT
;set value 1 to 50
; set value 2 to 50 Output:
(setq val1 50)
50
(setq val2 50)
50
;and operator NIL
(print (and val1 val2)) NIL

;or operator
(print (or val1 val2))

;not operator with value1


(print (not val1))

;not operator with value2


(print (not val2))
AND and OR
● AND evaluates its arguments from left to right.
● If a NIL is encountered, NIL is returned immediately. Any
remaining arguments are not even evaluated.
● Otherwise AND returns the value of its last argument.
● In other words, anything other than NIL behaves like T as
far as logical considerations are concerned. This is a great
feature.
● OR evaluates its arguments from left to right.
● If something other than NIL is encountered, it is returned
immediately.
● Any remaining arguments are not even evaluated.
Otherwise OR returns NIL.
AND and OR
● (AND (MEMBER 'DOG PETS) (MEMBER 'CAT PETS))
○ (CAT)
● (OR (MEMBER 'DOG PETS) (MEMBER 'CAT PETS))
○ (DOG CAT)
(write (atom 'abcd))
(terpri) When you execute the code, it returns the
(write (equal 'a 'b)) following result −

(terpri) T
NIL
(write (evenp 10)) T
(terpri) NIL
T
(write (evenp 7 )) NIL
(terpri) NIL
NIL
(write (oddp 7 )) T
(terpri)
(write (zerop 0.0000000001))
(terpri)
(write (eq 3 3.0 ))
(terpri)
(write (equal 3 3.0 ))
(terpri)
(write (null nil ))
COND Select a Value among
Alternatives
(COND
(condition1 action1 )
(condition2 action2 )
...
(conditionN actionN ) )
COND Select a Value among Alternatives
● If no successful clause is found, COND returns NIL.
● If the successful clause consists of only one element, then
the value of that element itself is returned.
(cond
((= n 1) "N equals 1")
(t "N doesn't equal 1")
)
Some facts about LISP
● LISP is Neither Call-by-reference nor Call-by-value
● The objects are s-expressions.
● Free-variable Values are Determined Dynamically, not
Lexically
● Function Names can be Used as Arguments
RECURSION AND ITERATION
● How a function can use itself in its own definition is called recursion.
● How a function can do something repeatedly without using recursion.
This is called iteration.
● A control structure is a general scheme by which a program can go about
getting things done.
● Recursion and iteration are examples of control structures.
LAMBDA Defines Anonymous Functions

● LISP allows you to write anonymous functions that are


evaluated only when they are encountered in the program.
● These functions are called Lambda functions.
● The syntax for the lambda expression is as follows −
● (lambda (parameters) body)
LAMBDA Defines Anonymous Functions

;lambda expression to get sum of product of four numbers


;mathematical expression is (val1*val2) + (val3*val4)

(write ((lambda (val1 val2 val3 val4)


(+ (* val1 val2) (+ (* val3 val4))))
;pass the values
2 4 6 8)
)
(terpri)
LAMBDA Defines Anonymous Functions

(write ((lambda (val1 val2 )


(* val1 val2))
;pass the values
10 20 )
)
Thank You

You might also like