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

Functional Programming - Lisp 2

Chapter 15 discusses functional programming languages, emphasizing their design based on mathematical functions as opposed to the imperative languages rooted in von Neumann architecture. It covers key concepts such as lambda expressions, higher-order functions, and the unique characteristics of languages like LISP, Scheme, and Haskell. The chapter concludes by comparing functional and imperative languages, highlighting the advantages and challenges of functional programming.

Uploaded by

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

Functional Programming - Lisp 2

Chapter 15 discusses functional programming languages, emphasizing their design based on mathematical functions as opposed to the imperative languages rooted in von Neumann architecture. It covers key concepts such as lambda expressions, higher-order functions, and the unique characteristics of languages like LISP, Scheme, and Haskell. The chapter concludes by comparing functional and imperative languages, highlighting the advantages and challenges of functional programming.

Uploaded by

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

Chapter 15

Functional
Programming
Languages

ISBN 0-321-49362-1
Introduction

• The design of the imperative languages is


based directly on the von Neumann
architecture
– Efficiency is the primary concern, rather than
the suitability of the language for software
development
• The design of the functional languages is
based on mathematical functions
– A solid theoretical basis that is also closer to
the user, but relatively unconcerned with the
architecture of the machines on which
programs will run

Copyright © 2015 Pearson. All rights reserved. 1-2


Mathematical Functions

• A mathematical function is a mapping of


members of one set, called the domain
set, to another set, called the range set
• A lambda expression specifies the
parameter(s) and the mapping of a
function in the following form
(x) x * x * x
for the function cube(x) = x * x * x

Copyright © 2015 Pearson. All rights reserved. 1-3


Lambda Expressions

• Lambda expressions describe nameless


functions
• Lambda expressions are applied to
parameter(s) by placing the parameter(s)
after the expression
e.g., ((x) x * x * x)(2)
which evaluates to 8

Copyright © 2015 Pearson. All rights reserved. 1-4


Functional Forms

• A higher-order function, or functional


form, is one that either takes functions as
parameters or yields a function as its
result, or both

Copyright © 2015 Pearson. All rights reserved. 1-5


Function Composition

• A functional form that takes two functions


as parameters and yields a function
whose value is the first actual parameter
function applied to the application of the
second
Form: h  f ° g
which means h (x)  f ( g ( x))
For f (x)  x + 2 and g (x)  3 * x,
h  f ° g yields (3 * x)+ 2

Copyright © 2015 Pearson. All rights reserved. 1-6


Apply-to-all
• A functional form that takes a single
function as a parameter and yields a list
of values obtained by applying the given
function to each element of a list of
parameters
Form: 
For h(x)  x * x
(h, (2, 3, 4)) yields (4, 9, 16)

Copyright © 2015 Pearson. All rights reserved. 1-7


Fundamentals of Functional
Programming Languages
• The objective of the design of a FPL is to mimic
mathematical functions to the greatest extent
possible
• The basic process of computation is fundamentally
different in a FPL than in an imperative language
– In an imperative language, operations are done and the
results are stored in variables for later use
– Management of variables is a constant concern and
source of complexity for imperative programming
• In an FPL, variables are not necessary, as is the case
in mathematics
• Referential Transparency - In an FPL, the evaluation of
a function always produces the same result given the
same parameters
Copyright © 2015 Pearson. All rights reserved. 1-8
Basic LISP Programming

loop
read in an expression from the console;
evaluate the expression;
print the result of evaluation to the console;
end loop.

1-9
Example
• LISP expressions are composed of forms. For example, cos(0) is
written as (cos 0).
• LISP expressions are case-insensitive. It makes no difference
whether we type (cos 0) or (COS 0).
• "+" is the name of the addition function that returns the sum of its
arguments.
• Numeric values like 4 and 6 are called self-evaluating forms: they
evaluate to themselves. To evaluate (+ 4 6) in applicative order,
the forms 4 and 6 are respectively evaluated to the values 4 and 6
before they are passed as arguments to the + function.

1-10
Numeric Functions

1-11
Define functions

• (defun double (x) (* x 2))


• DOUBLE
• In the above, we define a function named double,
which returns two times the value of its input
argument x.
• We can then test-drive the function as below:
(double 3)
• 6
• (double 7)
• 14

1-12
Programming in Lisp

1-13
Control Structures

• n! = 1 if n = 1
• n! = n * (n - 1)! if n > 1

1-14
Relation Operators

1-15
Multiple Recursions

1-16
Lists

• LISP is designed for 1. nil: Evaluating nil creates


symbolic computing. an empty list;
• The fundamental LISP 2. (cons x L): Given a LISP
object x and a list L,
data structure for evaluating (cons x L) create
supporting symbolic s a list
manipulation are lists containing x followed by
the elements in L.

1-17
Quote
• QUOTE - takes one parameter;
returns the parameter without
evaluation
– QUOTE is required because
the Scheme interpreter,
named EVAL, always
evaluates parameters to
function applications before
applying the function.
QUOTE is used to avoid
parameter evaluation when
it is not appropriate

– QUOTE can be abbreviated


with the apostrophe prefix
operator
'(A B) is equivalent to
(QUOTE (A B))

1-18
Basic List Functions
• Examples:
(CAR ′((A B) C D)) returns (A B)
(CAR ′A) is an error
(CDR ′((A B) C D)) returns (C D)
(CDR ′A) is an error
(CDR ′(A)) returns ()
(CONS ′() ′(A B)) returns (() A B)
(CONS ′(A B) ′(C D)) returns ((A B) C D)
(CONS ′A ′B) returns (A . B) (a dotted pair)

Dotted pair notation is a general syntax for cons cells that represents the CAR and CDR
explicitly. In this syntax, ( a . b ) stands for a cons cell whose CAR is the object a and
whose CDR is the object b . Dotted pair notation is more general than list syntax
because the CDR does not have to be a list.

Copyright © 2015 Pearson. All rights reserved. 1-19


List Functions (continued)

• LIST is a function for building a list from


any number of parameters
(LIST ′apple ′orange ′grape) returns
(apple orange grape)

Copyright © 2015 Pearson. All rights reserved. 1-20


Examples

Copyright © 2015 Pearson. All rights reserved. 1-21


Predicate Function: EQ?

• EQ? takes two expressions as parameters


(usually two atoms); it returns #T if both
parameters have the same pointer value;
otherwise #F
(EQ? 'A 'A) yields #T
(EQ? 'A 'B) yields #F
(EQ? 'A '(A B)) yields #F
(EQ? '(A B) '(A B)) yields #T or #F
(EQ? 3.4 (+ 3 0.4))) yields #T or #F

Copyright © 2015 Pearson. All rights reserved. 1-22


Predicate Function: EQV?

• EQV? is like EQ?, except that it works for both


symbolic and numeric atoms; it is a value
comparison, not a pointer comparison
(EQV? 3 3) yields #T
(EQV? 'A 3) yields #F
(EQV 3.4 (+ 3 0.4)) yields #T
(EQV? 3.0 3) yields #F (floats and integers are
different)

Copyright © 2015 Pearson. All rights reserved. 1-23


Predicate Functions: LIST? and NULL?

• LIST? takes one parameter; it returns #T if


the parameter is a list; otherwise #F
(LIST? '()) yields #T
• NULL? takes one parameter; it returns #T if
the parameter is the empty list; otherwise
#F
(NULL? '(())) yields #F

Copyright © 2015 Pearson. All rights reserved. 1-24


Structural Recursion with Lists

• (list-length ‘(1 2 3 4 5))


• Case 1: L is nil.
The length of an empty list is zero.
• Case 2: L is constructed by cons.
Then L is composed of two parts, namely, (first L) and (rest L). In such case,
the length of L can be obtained inductively by adding 1 to the length
of (rest L).

1-25
Example Scheme Function:
member
• LISP defines a function (member E L) that returns non-NIL if E is a member of L.

1-26
Example Scheme Function:
append
• LISP defines a function append that appends one list by another:

1-27
Tail Recursion

• Recursive functions are slow

• Tail-Recursive are more efficient

1-28
Functions as First-Class Objects

• A data type is first-class in a programming language


when you can pass instances of the data type as
function arguments or return them as function
values.
• (defun double (x) (* 2 x))
• (double (double (double (double 1))))

• It works but it is clumsy

1-29
Functions as First-Class Objects

• Applying a given transformation F on X for N times by simply writing


• (repeat-transformation F N X)

• The definition follows the standard tail recursive pattern.


• Notice the form (funcall F X).
• Given a function F and objects X1 X2 ... Xn, the
form (funcall F X1 X2 ... Xn) invoke the function F with
arguments X1, X2, ..., Xn.
• The variable N is a counter keeping track of the remaining number of times we
need to apply function F to the accumulator variable X.

(repeat-transformation (function double) 4 1))


16
1-30
Iterating Through a List

(mapfirst #'double '(1 2 3 4 5))


(2 4 6 8 10)

When we want Common LISP to interpret a name F as a function, instead of


typing (function F), we can also type the shorthand #'F. The prefix #' is nothing but
an alternative syntax for the closure constructor.

1-31
Functions Returning Multiple Values

(defun order (a b)
"Return two values: (min a b) and (max a
b)." (if (>= a b)
(values b a)
(values a b)))

The values special form returns its arguments as


multiple values.

Copyright © 2015 Pearson. All rights reserved. 1-32


Support for Functional Programming in
Primarily Imperative Languages
• Support for functional programming is
increasingly creeping into imperative
languages
– Anonymous functions (lambda expressions)
• JavaScript: leave the name out of a function
definition
• C#: i => (i % 2) == 0 (returns true or false
depending on whether the parameter is even or
odd)
• Python: lambda a, b : 2 * a - b

Copyright © 2015 Pearson. All rights reserved. 1-33


Support for Functional Programming in
Primarily Imperative Languages
(continued)
• Python supports the higher-order functions filter
and map (often use lambda expressions as their
first parameters)
map(lambda x : x ** 3, [2, 4, 6, 8])
Returns [8, 64, 216, 512]
• Python supports partial function applications
from operator import add
add5 = partial (add, 5)
(the first line imports add as a function)
Use: add5(15)

Copyright © 2015 Pearson. All rights reserved. 1-34


Support for Functional Programming in
Primarily Imperative Languages (continued)

• Ruby Blocks
– Are effectively subprograms that are sent to
methods, which makes the method a higher-
order subprogram
– A block can be converted to a subprogram
object with lambda
times = lambda {|a, b| a * b}
Use: x = times.(3, 4) (sets x to 12)
– Times can be curried with
times5 = times.curry.(5)
Use: x5 = times5.(3) (sets x5 to 15)
Copyright © 2015 Pearson. All rights reserved. 1-35
Comparing Functional and Imperative
Languages
• Imperative Languages:
– Efficient execution
– Complex semantics
– Complex syntax
– Concurrency is programmer designed
• Functional Languages:
– Simple semantics
– Simple syntax
– Less efficient execution
– Programs can automatically be made
concurrent

Copyright © 2015 Pearson. All rights reserved. 1-36


Summary
• Functional programming languages use function
application, conditional expressions, recursion, and
functional forms to control program execution
• Lisp began as a purely functional language and later
included imperative features
• Scheme is a relatively simple dialect of Lisp that uses static
scoping exclusively
• Common Lisp is a large Lisp-based language
• ML is a static-scoped and strongly typed functional
language that uses type inference
• Haskell is a lazy functional language supporting infinite
lists and set comprehension.
• F# is a .NET functional language that also supports
imperative and object-oriented programming
• Some primarily imperative languages now incorporate
some support for functional programming
• Purely functional languages have advantages over
imperative alternatives, but still are not very widely used

Copyright © 2015 Pearson. All rights reserved. 1-37

You might also like