You are on page 1of 81

CS212: Principles of Programming Languages

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


Syllabus
IV. Functional Programming Languages (FPL)
Introduction to FPL: Fundamentals and Elements of FPL, Function Declaration, Expression Evaluation, Application
of Functional Programming Languages, Comparison of Functional and Imperative Languages
Type Checking: Type Inference, Type Names and Type Equivalence, Coercion
Case Studies: LISP, Haskel

PRINCIPLES OF PROGRAMMING LANGUAGES


Unit 4 Functional Programming Languages
Introduction
Mathematical Functions
Fundamentals of Functional Programming Languages
The First Functional Programming Language: LISP
Type checking and Inference
COMMON LISP
ML
Haskell
Applications of Functional Languages
Comparison of Functional and Imperative Languages

PRINCIPLES OF PROGRAMMING LANGUAGES


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

PRINCIPLES OF PROGRAMMING LANGUAGES


Lazy Evaluation
◦ A language is strict if it requires all actual parameters to be fully evaluated
◦ A language is nonstrict if it does not have the strict requirement
◦ Nonstrict languages are more efficient and allow some interesting capabilities – infinite lists
◦ Lazy evaluation - Only compute those values that are necessary
◦ Positive numbers
positives = [0..]
◦ Determining if 16 is a square number
member b [] = False
member b(a:x)= (a == b)||member x b
squares = [n * n | n ← [0..]]
member squares 16

PRINCIPLES OF PROGRAMMING LANGUAGES


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
◦ During evaluation, the mapping of a function contains no unbound
parameters, where a bound parameter is a name for a particular value.
◦ Every occurrence of a parameter is bound to a value from the domain set and
is a constant during evaluation.

PRINCIPLES OF PROGRAMMING LANGUAGES


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

PRINCIPLES OF PROGRAMMING LANGUAGES


Example of Function Definition
x.x is a way of expressing the identity function f(x) = x without having
to give it a name.

x.2x represents the function f(x) = 2x

PRINCIPLES OF PROGRAMMING LANGUAGES


Bound and Free Variables
A bound variable is a variable that is in the scope of a declaration
(lambda binding) for that variable. A variable that is not bound is
free. In the expression:
x. y.(x z)
x is bound and z is free (the y-binding has no effect as there is no y
in the body of the expression)
 Examples: x. y.(yz) x.(x b)

PRINCIPLES OF PROGRAMMING LANGUAGES


Scope of Lambda Bindings
In the expression x.F, the scope of the declaration (or lambda binding) x is
limited to F.

x y x x yx x)

PRINCIPLES OF PROGRAMMING LANGUAGES


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

PRINCIPLES OF PROGRAMMING LANGUAGES


Function Composition
oA 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

PRINCIPLES OF PROGRAMMING LANGUAGES


Functional Composition
FLs rely on functional composition instead of sequence.
f(x) = x + 1
g(x) = x * 2
Instead of (imperative style)
x = x + 1;
x = x * 2;
we say g(f(x))

PRINCIPLES OF PROGRAMMING LANGUAGES


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)

PRINCIPLES OF PROGRAMMING LANGUAGES


Fundamentals and Elements 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

PRINCIPLES OF PROGRAMMING LANGUAGES


Fundamentals and Elements of Functional Programming
Languages - continued
◦ Referential Transparency - In an FPL, the evaluation of a
function always produces the same result given the same
parameters
result1 = (fun(a) + b) / (fun(a) - c);
temp = fun(a);
result2 = (temp + b) / (temp - c);

PRINCIPLES OF PROGRAMMING LANGUAGES


Fundamentals and Elements of Functional
Programming Languages - continued
o Tail Recursion – Writing recursive functions that can be
automatically converted to iteration
(DEFINE (member atm a_list)
(COND
((NULL? a_list) #F)
((EQ? atm (CAR a_list)) #T)
(ELSE (member atm (CDR a_list)))
)
)

PRINCIPLES OF PROGRAMMING LANGUAGES


What is a Data Type?
• A type is a collection of computational entities that share some common
property 
• Programming languages are designed to help programmers organize
computational constructs and use them correctly. Many programming
languages organize data and computations into collections called types.

• Some examples of types are: 


o the type Int of integers
o the type (Int→Int) of functions from integers to integers

PRINCIPLES OF PROGRAMMING LANGUAGES


Why do we need them?
•Consider “untyped” universes:
•Bit string in computer memory
•λ-expressions in λ calculus
•Sets in set theory
•“untyped” = there’s only 1 type
•Types arise naturally to categorize objects according to patterns of
use
• E.g. all integer numbers have same set of applicable operations

PRINCIPLES OF PROGRAMMING LANGUAGES


Use of Types
• Identifying and preventing meaningless errors in the program
o Compile-time checking
o Run-time checking
• Program Organization and documentation
o Separate types for separate concepts
o Indicates intended use declared identifiers
• Supports Optimization
o Short integers require fewer bits
o Access record component by known offset

PRINCIPLES OF PROGRAMMING LANGUAGES


Type Errors
•A type error occurs when a computational entity, such as a
function or a data value, is used in a manner that is inconsistent
with the concept it represents
•Languages represent values as sequences of bits. A "type error"
occurs when a bit sequence written for one type is used as a bit
sequence for another type
•A simple example can be assigning a string to an integer or using
addition to add an integer or a string

PRINCIPLES OF PROGRAMMING LANGUAGES


Type Systems
•A tractable syntactic framework for classifying phrases
according to the kinds of values they compute
• By examining the flow of these values, a type system
attempts to prove that no type errors can occur 
•Seeks to guarantee that operations expecting a certain
kind of value are not used with values for which that
operation does not make sense

PRINCIPLES OF PROGRAMMING LANGUAGES


Type Safety
A programming language is type safe if no program is allowed to violate its type
distinctions
Example of current languages:
Not Safe : C and C++
Type casts, pointer arithmetic
Almost Safe : Pascal
Explicit deallocation; dangling pointers
Safe : Lisp, Smalltalk, ML, Haskell, Java, Scala
Complete type checking

PRINCIPLES OF PROGRAMMING LANGUAGES


Type Checking – Compile Time
• Check types at compile time, before a program is started
• In these languages, a program that violates a type constraint is not compiled
and cannot be executed
Expressiveness of the Compiler:
a) sound
    If no programs with errors are considered correct
b) conservative
     if some programs without errors are still considered
     to have errors (especially in the case of type-safe languages )
PRINCIPLES OF PROGRAMMING LANGUAGES
Type Checking – Run Time
•The compiler generates the code
•When an operation is performed, the code checks to  make sure that
the operands have the correct type
Combining the Compile and Run time
•Most programming languages use some combination of compile-time
and run-time type checking
• In Java, for example, static type checking is used to distinguish arrays
from integers, but array bounds errors are checked at run time.

PRINCIPLES OF PROGRAMMING LANGUAGES


Type Declaration
Two basic kinds of type declaration:
1. transparent
o  meaning an alternative name is given to a type that can also be expressed
without this name
For example, in C, the statements,
typedef char byte; 
typedef byte ten bytes[10];  
the first, declaring a type byte that is equal to char and the second an array type
ten bytes that is equal to arrays of 10 bytes
PRINCIPLES OF PROGRAMMING LANGUAGES
Type Declaration
2. Opaque
Opaque, meaning a new type is introduced into the program that is not equal to any other
type
Example in C,
typedef struct Node{
    int val;
    struct Node *left;
    struct Node* right;
}N;
PRINCIPLES OF PROGRAMMING LANGUAGES
Type Inference
•Process of identifying the type of the expressions based on the type
of the symbols that appear in them
•Similar to the concept of compile type checking
o All information is not specified
o Some degree of logical inference required
• Some languages that include Type Inference are Visual
Basic (starting with version 9.0), C# (starting with version 3.0), Clean,
Haskell, ML, OCaml, Scala 
•This feature is also being planned and introduced for C+
+0x and Perl6
PRINCIPLES OF PROGRAMMING LANGUAGES
Type Inference

Example: Compile Time checking:


For language, C:
int addone(int x) {
     int result;     /*declare integer result (C language)*/ 
     result = x+1; 
     return result; 
}
Lets look at the following example,
addone(x) {    
    val result;      /*inferred-type result */        
    result = x+1;        
    return result;
}
PRINCIPLES OF PROGRAMMING LANGUAGES
Type Checking
•Two major approaches: structural equivalence and name
equivalence
–Name equivalence is based on declarations
–Structural equivalence is based on some notion of meaning
behind those declarations
–Name equivalence is more fashionable these days

PRINCIPLES OF PROGRAMMING LANGUAGES


Name Equivalence
•There are at least two common variants on name
equivalence
–The differences between all these approaches boils down to
where you draw the line between important and unimportant
differences between type descriptions
–In all three schemes described , we begin by putting every type
description in a standard form that takes care of "obviously
unimportant" distinctions like those above

PRINCIPLES OF PROGRAMMING LANGUAGES


Name Equivalence
For example, the issue of aliasing. Should aliased types be considered the same?
Example:
TYPE cel_temp = REAL;
faren_temp = REAL;
VAR c : cel_temp;
f : faren_temp;

f := c; (* should this raise an error? *)
•With strict name equivalence, the above raises an error. Loose name equivalence would allow
it.

PRINCIPLES OF PROGRAMMING LANGUAGES


Structural Equivalence
•Structural equivalence depends on simple comparison of
type descriptions substitute out all names
–expand all the way to built-in types

•Original types are equivalent if the expanded type


descriptions are the same

PRINCIPLES OF PROGRAMMING LANGUAGES


Type Casting
Most programming languages allow some form of type conversion (or casting),
where the programmer can change one type of variable to another.
We saw a lot of this in Python:
◦ Every print statement implicitly cast variables to be strings. We even
coded this in our own classes.
◦ Example from Point class:
def __init__(self):
return ‘<‘ + str(self._x) + ‘,’ + str(self._y) + ‘>’

PRINCIPLES OF PROGRAMMING LANGUAGES


Type Casting
Coercion
◦ When an expression of one type is used in a context where a
different type is expected, one normally gets a type error
◦ But what about
var a : integer; b, c : real;
...
c := a + b;

PRINCIPLES OF PROGRAMMING LANGUAGES


Type Casting
•Coercion
–Many languages allow things like this, and COERCE an
expression to be of the proper type
–Coercion can be based just on types of operands, or can take
into account expected type from surrounding context as well
–Fortran has lots of coercion, all based on operand type

PRINCIPLES OF PROGRAMMING LANGUAGES


Type Coercion
•C has lots of coercion, too, but with simpler rules:
–all floats in expressions become doubles
–short int and char become int in expressions
–if necessary, precision is removed when assigning into LHS

PRINCIPLES OF PROGRAMMING LANGUAGES


LISP Data Types and Structures
◦ Data object types: originally only atoms and lists
◦ List form: parenthesized collections of sublists
and/or atoms
e.g., (A B (C D) E)
◦ Originally, LISP was a typeless language
◦ LISP lists are stored internally as single-linked lists

PRINCIPLES OF PROGRAMMING LANGUAGES


LISP Interpretation
◦ Lambda notation is used to specify functions and function definitions. Function applications
and data have the same form.
e.g., If the list (A B C) is interpreted as data it is
a simple list of three atoms, A, B, and C
If it is interpreted as a function application,
it means that the function named A is
applied to the two parameters, B and C
◦ The first LISP interpreter appeared only as a demonstration of the
universality of the computational capabilities of the notation

PRINCIPLES OF PROGRAMMING LANGUAGES


Evaluation
◦ Parameters are evaluated, in no particular order
◦ The values of the parameters are substituted into the
function body
◦ The function body is evaluated
◦ The value of the last expression in the body is the value
of the function

PRINCIPLES OF PROGRAMMING LANGUAGES


Primitive Functions
◦ Arithmetic: +, -, *, /, ABS, SQRT, REMAINDER, MIN,
MAX
e.g., (+ 5 2) yields 7
◦ 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))

PRINCIPLES OF PROGRAMMING LANGUAGES


Function Definition: LAMBDA
◦ Lambda Expressions
◦ Form is based on  notation
e.g., (LAMBDA (x) (* x x)
x is called a bound variable
◦ Lambda expressions can be applied
e.g., ((LAMBDA (x) (* x x)) 7)

PRINCIPLES OF PROGRAMMING LANGUAGES


Special Form Function: DEFINE
A Function for Constructing Functions DEFINE - Two forms:
1. To bind a symbol to an expression
e.g., (DEFINE pi 3.141593)
Example use: (DEFINE two_pi (* 2 pi))
2. To bind names to lambda expressions
e.g., (DEFINE (square x) (* x x))
Example use: (square 5)
- The evaluation process for DEFINE is different! The first parameter is
never evaluated. The second parameter is evaluated and bound to the
first parameter.

PRINCIPLES OF PROGRAMMING LANGUAGES


Output Functions
◦ (DISPLAY expression)
◦ (NEWLINE)

PRINCIPLES OF PROGRAMMING LANGUAGES


Numeric Predicate Functions
◦ #T is true and #F is false (sometimes () is used
for false)
◦ =, <>, >, <, >=, <=
◦ EVEN?, ODD?, ZERO?, NEGATIVE?

PRINCIPLES OF PROGRAMMING LANGUAGES


Control Flow: IF
◦ Selection- the special form, IF
(IF predicate then_exp else_exp)
e.g.,
(IF (<> count 0)
(/ sum count)
0)

PRINCIPLES OF PROGRAMMING LANGUAGES


Control Flow: COND

◦ Multiple Selection - the special form, COND


General form:
(COND
(predicate_1 expr {expr})
(predicate_1 expr {expr})
...
(predicate_1 expr {expr})
(ELSE expr {expr}))
◦ Returns the value of the last expression in the first pair whose predicate evaluates
to true

PRINCIPLES OF PROGRAMMING LANGUAGES


Example of COND
(DEFINE (compare x y)
(COND
((> x y) “x is greater than y”)
((< x y) “y is greater than x”)
(ELSE “x and y are equal”)
)
)

PRINCIPLES OF PROGRAMMING LANGUAGES


List Functions: CONS and LIST
◦ CONS takes two parameters, the first of which can be either an
atom or a list and the second of which is a list; returns a new
list that includes the first parameter as its first element and
the second parameter as the remainder of its result
e.g., (CONS 'A '(B C)) returns (A B C)
◦ LIST takes any number of parameters; returns a list with the
parameters as elements

PRINCIPLES OF PROGRAMMING LANGUAGES


List Functions: CAR and CDR
◦ CAR takes a list parameter; returns the first element of that list
e.g., (CAR '(A B C)) yields A
(CAR '((A B) C D)) yields (A B)
◦ CDR takes a list parameter; returns the list after removing its
first element
e.g., (CDR '(A B C)) yields (B C)
(CDR '((A B) C D)) yields (C D)

PRINCIPLES OF PROGRAMMING LANGUAGES


Predicate Function: EQ?
◦ EQ? takes two symbolic parameters; it returns #T if
both parameters are atoms and the two are the same;
otherwise #F
e.g., (EQ? 'A 'A) yields #T
(EQ? 'A 'B) yields #F
◦ Note that if EQ? is called with list parameters, the
result is not reliable
◦ Also EQ? does not work for numeric atoms
PRINCIPLES OF PROGRAMMING LANGUAGES
Predicate Functions: LIST? and
NULL?
◦ LIST? takes one parameter; it returns #T if the
parameter is a list; otherwise #F
◦ NULL? takes one parameter; it returns #T if the
parameter is the empty list; otherwise #F
◦ Note that NULL? returns #T if the parameter is()

PRINCIPLES OF PROGRAMMING LANGUAGES


Example Function: member
◦ member takes an atom and a simple list; returns #T if the atom is
in the list; #F otherwise
DEFINE (member atm lis)
(COND
((NULL? lis) #F)
((EQ? atm (CAR lis)) #T)
((ELSE (member atm (CDR lis)))
))

PRINCIPLES OF PROGRAMMING LANGUAGES


Example Function: equalsimp
◦ equalsimp takes two simple lists as parameters; returns #T if the two simple lists
are equal; #F otherwise
(DEFINE (equalsimp lis1 lis2)
(COND
((NULL? lis1) (NULL? lis2))
((NULL? lis2) #F)
((EQ? (CAR lis1) (CAR lis2))
(equalsimp(CDR lis1)(CDR lis2)))
(ELSE #F)
))

PRINCIPLES OF PROGRAMMING LANGUAGES


Example Function: equal
◦ equal takes two general lists as parameters; returns #T if the two lists are equal; #F otherwise
(DEFINE (equal lis1 lis2)
(COND
((NOT (LIST? lis1))(EQ? lis1 lis2))
((NOT (LIST? lis2)) #F)
((NULL? lis1) (NULL? lis2))
((NULL? lis2) #F)
((equal (CAR lis1) (CAR lis2))
(equal (CDR lis1) (CDR lis2)))
(ELSE #F)
))

PRINCIPLES OF PROGRAMMING LANGUAGES


Example Function: append
◦ append takes two lists as parameters; returns the first parameter
list with the elements of the second parameter list appended at
the end
(DEFINE (append lis1 lis2)
(COND
((NULL? lis1) lis2)
(ELSE (CONS (CAR lis1)
(append (CDR lis1) lis2)))
))

PRINCIPLES OF PROGRAMMING LANGUAGES


Example Function: LET
◦ General form:
(LET (
(name_1 expression_1)
(name_2 expression_2)
...
(name_n expression_n))
body
)
◦ Evaluate all expressions, then bind the values to the names; evaluate the
body

PRINCIPLES OF PROGRAMMING LANGUAGES


LET Example
(DEFINE (quadratic_roots a b c)
(LET (
(root_part_over_2a
(/ (SQRT (- (* b b) (* 4 a c)))(* 2 a)))
(minus_b_over_2a (/ (- 0 b) (* 2 a)))
(DISPLAY (+ minus_b_over_2a root_part_over_2a))
(NEWLINE)
(DISPLAY (- minus_b_over_2a root_part_over_2a))
))

PRINCIPLES OF PROGRAMMING LANGUAGES


Tail Recursion
◦ Definition: A function is tail recursive if its recursive call is
the last operation in the function
◦ A tail recursive function can be automatically converted
by a compiler to use iteration, making it faster
◦ Scheme language definition requires that Scheme
language systems convert all tail recursive functions to
use iteration

PRINCIPLES OF PROGRAMMING LANGUAGES


Tail Recursion in - continued
◦ Example of rewriting a function to make it tail recursive, using helper a function
Original: (DEFINE (factorial n)
(IF (= n 0)
1
(* n (factorial (- n 1)))
))
Tail recursive: (DEFINE (facthelper n factpartial)
(IF (= n 0)
factpartial
facthelper((- n 1) (* n factpartial)))
))
(DEFINE (factorial n)
(facthelper n 1))

PRINCIPLES OF PROGRAMMING LANGUAGES


Functional Forms
◦ Composition
◦ The previous examples have used it
◦ (CDR (CDR '(A B C))) returns (C)
◦ Apply to All - one form in Scheme is mapcar
◦ Applies the given function to all elements of the given list;
(DEFINE (mapcar fun lis)
(COND
((NULL? lis) ())
(ELSE (CONS (fun (CAR lis))
(mapcar fun (CDR lis))))
))
PRINCIPLES OF PROGRAMMING LANGUAGES
Adding a List of Numbers
((DEFINE (adder lis)
(COND
((NULL? lis) 0)
(ELSE (EVAL (CONS '+ lis)))
))
◦ The parameter is a list of numbers to be added; adder inserts a + operator and
evaluates the resulting list
◦ Use CONS to insert the atom + into the list of numbers.
◦ Be sure that + is quoted to prevent evaluation
◦ Submit the new list to EVAL for evaluation

PRINCIPLES OF PROGRAMMING LANGUAGES


COMMON LISP
A combination of many of the features of the popular dialects of LISP around in the
early 1980s
A large and complex language--the opposite of Scheme
Features include:
◦ records
◦ arrays
◦ complex numbers
◦ character strings
◦ powerful I/O capabilities
◦ packages with access control
◦ iterative control statements

PRINCIPLES OF PROGRAMMING LANGUAGES


Haskell
◦ Similar to ML (syntax, static scoped, strongly typed, type inferencing, pattern matching)
◦ Different from ML (and most other functional languages) in that it is purely functional
(e.g., no variables, no assignment statements, and no side effects of any kind)
Syntax differences from ML
fact 0 = 1
fact n = n * fact (n – 1)

fib 0 = 1
fib 1 = 1
fib (n + 2) = fib (n + 1) + fib n

PRINCIPLES OF PROGRAMMING LANGUAGES 64


Function Definitions with Different
Parameter Ranges
fact n
| n == 0 = 1
| n > 0 = n * fact(n – 1)

sub n
| n < 10 = 0
| n > 100 = 2
| otherwise = 1

square x = x * x

- Works for any numeric type of x

PRINCIPLES OF PROGRAMMING LANGUAGES


Lists
◦ List notation: Put elements in brackets
e.g., directions = ["north",
"south", "east", "west"]
◦ Length: #
e.g., #directions is 4
◦ Arithmetic series with the .. operator
e.g., [2, 4..10] is [2, 4, 6, 8, 10]
◦ Catenation is with ++
e.g., [1, 3] ++ [5, 7] results in [1, 3, 5, 7]
◦ CONS, CAR, CDR via the colon operator (as in Prolog)
e.g., 1:[3, 5, 7] results in [1, 3, 5, 7]

PRINCIPLES OF PROGRAMMING LANGUAGES


Factorial Revisited
product [] = 1
product (a:x) = a * product x

fact n = product [1..n]

PRINCIPLES OF PROGRAMMING LANGUAGES


List Comprehension
◦ Set notation
◦ List of the squares of the first 20 positive integers: [n * n | n
← [1..20]]
◦ All of the factors of its given parameter:
factors n = [i | i ← [1..n ̀ div̀2],
n ̀ mod̀i == 0]

PRINCIPLES OF PROGRAMMING LANGUAGES


Quicksort
sort [] = []
sort (a:x) =
sort [b | b ← x; b <= a] ++
[a] ++
sort [b | b ← x; b > a]

PRINCIPLES OF PROGRAMMING LANGUAGES


Lazy Evaluation
◦ A language is strict if it requires all actual parameters to be fully evaluated
◦ A language is nonstrict if it does not have the strict requirement
◦ Nonstrict languages are more efficient and allow some interesting capabilities
– infinite lists
◦ Lazy evaluation - Only compute those values that are necessary
◦ Positive numbers
positives = [0..]
◦ Determining if 16 is a square number
member [] b = False
member(a:x) b=(a == b)||member x b
squares = [n * n | n ← [0..]]
member squares 16

PRINCIPLES OF PROGRAMMING LANGUAGES


Member Revisited
◦ The member function could be written as:
member [] b = False
member(a:x) b=(a == b)||member x b
◦ However, this would only work if the parameter to squares was a perfect
square; if not, it will keep generating them forever. The following version will
always work:
member2 (m:x) n
| m < n = member2 x n
| m == n = True
| otherwise = False

PRINCIPLES OF PROGRAMMING LANGUAGES


Applications of Functional Languages
◦ LISP is used for
◦ artificial intelligence
◦ Knowledge representation
◦ Machine learning
◦ Natural language processing
◦ Modeling of speech and vision

PRINCIPLES OF PROGRAMMING LANGUAGES


Comparing Functional and Imperative Languages

◦ Imperative Languages:
◦ Efficient execution
◦ Complex semantics
◦ Complex syntax
◦ Concurrency is programmer designed
◦ Functional Languages:
◦ Simple semantics
◦ Simple syntax
◦ Inefficient execution
◦ Programs can automatically be made concurrent

PRINCIPLES OF PROGRAMMING LANGUAGES


What is the main Focus of FP?
Unlike OOP Languages, All FP Language Programs mainly focus on “What you are doing” or
“What is to be done”.
They mainly focus on the following things:
What Information is desired that is Inputs.
What Transformations are required that is Actual Logic.
That means FP is mainly focused on “What is to be done”. It does not much focus on “How is it
to be done”

PRINCIPLES OF PROGRAMMING LANGUAGES


Main Characteristics of Imperative Programming?

Any Imperative Programming (IP) Languages can contain the following Characteristics:
Sequence of Statements.
Order of execution of Statements is very important.
Stateful Programming Model.
They contain state.(In information technology and computer science, a program
is described as stateful if it is designed to remember preceding events or user
interactions;  the remembered information is called the state of the system.)
They use both Immutable and Mutable Data.
They can change state. They directly change the state of Program.
They may have Side-effects.
They represent state with Data Fields.

PRINCIPLES OF PROGRAMMING LANGUAGES


Differences between FP and OOP(IP)?

Functional Programming OOP

Does not exist State Exists State

Main Focus on: “What you are doing” Main focus on “How you are doing”

Functions with No-Side Effects Methods with Side Effects

Functions are first-class citizens Objects are first-class citizens

Primary Manipulation Unit is Objects(Instances of


Primary Manipulation Unit is “Function”
Classes)

Order of execution is less importance. Order of execution is must and very important.

Stateless Programming Model Stateful Programming Model

PRINCIPLES OF PROGRAMMING LANGUAGES


Differences between FP and Imperative(IP)?

Characteristic Imperative Approach Functional Approach


How to perform tasks What information is desired and
Programmer focus (algorithms) and how to track what transformations are
changes in state required
State changes Important Non-existent
Order of execution Important Low importance
Loops, conditionals, and Function calls, including
Primary flow control
function (method) calls recursion
Instances of structures or Functions as first-class objects
Primary manipulation unit
classes and data collections

PRINCIPLES OF PROGRAMMING LANGUAGES


FAQs

Q1. What is a "functional programming language"?


Q2. What is LISP
Q3. What are the features of Haskell Language.
Q4.Explain the concept of lambda expression with example.
Q.5 Differentiate between Lazy and Eager evaluation.

PRINCIPLES OF PROGRAMMING LANGUAGES


Practice Assignments

1. What is output of the following:


(prog ((x '(a b c))(y '(1 2 3))(z '(p q 10))) (format t "x = ~a y =
~a z = ~a" x y z))
2. Write a function split that takes a Boolean separator
function and a list, and returns a list of lists, where the
elements of the list that are adjacent (not separated by a
separator) are in the lists in the result in Haskell

PRINCIPLES OF PROGRAMMING LANGUAGES


Takeaway
 Functional programming languages use function application, conditional
expressions, recursion, and functional forms to control program execution
instead of imperative features such as variables and assignments
 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 which includes
type inference, exception handling, and a variety of data structures and
abstract data types
 Haskell is a lazy functional language supporting infinite lists and set
comprehension.
 Purely functional languages have advantages over imperative alternatives, but
their lower efficiency on existing machine architectures has prevented them
from enjoying widespread use

PRINCIPLES OF PROGRAMMING LANGUAGES


References
Robert W. Sebesta , “Concepts of Programming Languages”

PRINCIPLES OF PROGRAMMING LANGUAGES

You might also like