Docsity

Functional Programming - Lecture Notes | ECS 140A, Assignments of Programming Languages

Toggle sidebar
bg1
Functional Programming
Introduction
•Talked about features of imperative language:
– Notion of states (through named locations),
– transformation of states through various statements and
expressions: hence a notion of sequencing to permit
precise and deterministic control over the state.
a = 1;
while (n > 0) {a = a*n; n = n -1; }
•Functional programming languages: a family of languages in
which entire computation is carried out through evaluation of
expressions: implicit state.
•In functional programming languages, computation is carried
out by carrying around the state explicitly rather than
implicitly, and looping is accomplished via recursion
fac n = 1 if n = 1
= n * (fac n-1)
n and result: stores the state of computation.
•Functional programming often described as “what is being
computed” rather than “how is it computed.”
•What if drop assignment statement and any other side-effect
primitives? The purely functional subset of most imperative
languages is very weak: lack of higher order functions, lazy
evaluation, pattern matching, etc.
•Example languages: Lisp and its derivations (?), FP, Miranda,
ML, Haskell
ECS140A, Winter’06 Common Lisp, slide 1 c
Raju Pandey
LISP (LIST processing)
•Look at some interesting features (not all)
•Compare/contrast to those that we have seen
•History: Developed by John McCarthy at MIT in late 50’s;
Second oldest language; Originally intended for AI
applications; Many variants: MacLisp, INTERLISP, Franz
LISP, Common LISP, Scheme (pretty different), etc.
•Common Lisp: synthesis of many variations of LISP in an
effort to standardize the language. Many implementations
available: kcl, gcl, clisp, etc.
How do you program in lisp?
•Different from compile-link-execute. Instead, interact with an
interpreter: read-execute-output.
(defun sum (n) int sum(int n) {
(let ((s 0)) int i, s = 0;
(dotimes (i n s) for (i = 0; i < n; i++)
(incf s i)))) s += i;
return(s);
}
•What about a function that takes a number n and returns a
function that adds n to its argument?
(defun addn (n)
’(lamda (x) (+ x n)))
•The interpreter repeatedly reads your program, determines
its structure on the fly, and execute it ⇒provides an
execution environment, and will remember from one program
to another.
> (* 8 3)
24
> (+ 2 (* 3 4))
14
> (cons ’a ’(b c))
(A B C)
•Interpreter also provides mechanisms for debugging..
ECS140A, Winter’06 Common Lisp, slide 2 c
Raju Pandey
Basics
•(Nearly) everything (program and data) is represented by an
s-expression (symbolic expression).
Why? Programs could generate programs (AI motivation)
•Two kinds of s-exprs: Atoms and Lists.
•Atoms: Defines symbols and numbers.
– Symbols: Denote names that can be bound to objects.
Represented using identifiers
Example: A, CAR, B12, NIL, xyz
LISP does not distinguish between upper and lowercase
– Numbers: integers and reals.
Example: 1, 2.3, 456
•nil represents false,and anything not nil represents true.
Note that nil represents both empty list and false. Talso
used for representing true value.
•Lists: Constructed from atoms and lists. So programs and
data both represented as lists.
Representation: surround the elements of the list by (and )
(): empty list
(1 2): list with 2 elements
(a (b c)): list with 2 elements
•LISP provides a number of functions for manipulating lists.
•Further, lists are nice vehicle for recursive programming.
ECS140A, Winter’06 Common Lisp, slide 3 c
Raju Pandey
Symbols and variables
•Symbols can be used to name variables, functions.
•They can be assigned values just like in other languages
•Symbols as variables:
> (setq x 5)
5
> (+ x 6)
11
> (+ 2 (setq x (* 3 4)))
14
> x
12
•symbols can also be assigned values through setf:
> (setf *glob* 98)
98
> (setf x (list ’a ’b ’c ’a))
(a b c a)
> (setf (car x) ’n)
N
> x
(N B C A)
In the above example, value of a in list x is replaced by N: If
the first argument of setf is an expression, the value of the
second argument is inserted in the place referred to by the
first.
•Symbols as functions: functions such as +, -, setq are
denotes as symbols, except that they have a function value
•In LISP, same name can denote a variable and a function.
The two are treated differently:
> (1+ 2)
3
> (setq 1+ 5)
> (1+ 1+ 5)
10
ECS140A, Winter’06 Common Lisp, slide 4 c
Raju Pandey
pf3
pf4

Partial preview of the text

Download Functional Programming - Lecture Notes | ECS 140A and more Assignments Programming Languages in PDF only on Docsity!

Functional Programming

Introduction

• Talked about features of imperative language:

  • Notion of states (through named locations),
  • transformation of states through various statements and expressions: hence a notion of sequencing to permit precise and deterministic control over the state. a = 1; while (n > 0) { a = a*n; n = n -1; }

• Functional programming languages: a family of languages in

which entire computation is carried out through evaluation of expressions: implicit state.

• In functional programming languages, computation is carried

out by carrying around the state explicitly rather than implicitly, and looping is accomplished via recursion fac n = 1 if n = 1 = n * (fac n-1) n and result: stores the state of computation.

• Functional programming often described as “what is being

computed” rather than “how is it computed.”

• What if drop assignment statement and any other side-effect

primitives? The purely functional subset of most imperative languages is very weak: lack of higher order functions, lazy evaluation, pattern matching, etc.

• Example languages: Lisp and its derivations (?), FP, Miranda,

ML, Haskell

ECS140A, Winter’06 Common Lisp, slide 1 ©c Raju Pandey

LISP ( LIST processing )

• Look at some interesting features (not all)

• Compare/contrast to those that we have seen

• History: Developed by John McCarthy at MIT in late 50’s;

Second oldest language; Originally intended for AI applications; Many variants: MacLisp, INTERLISP, Franz LISP, Common LISP, Scheme (pretty different), etc.

• Common Lisp: synthesis of many variations of LISP in an

effort to standardize the language. Many implementations available: kcl, gcl, clisp, etc. How do you program in lisp?

• Different from compile-link-execute. Instead, interact with an

interpreter : read-execute-output. (defun sum (n) int sum(int n) { (let ((s 0)) int i, s = 0; (dotimes (i n s) for (i = 0; i < n; i++) (incf s i)))) s += i; return(s); }

• What about a function that takes a number n and returns a

function that adds n to its argument? (defun addn (n) ’(lamda (x) (+ x n)))

• The interpreter repeatedly reads your program, determines

its structure on the fly, and execute it ⇒ provides an

execution environment, and will remember from one program to another.

(* 8 3) 24 (+ 2 (* 3 4)) 14 (cons ’a ’(b c)) (A B C)

• Interpreter also provides mechanisms for debugging..

ECS140A, Winter’06 Common Lisp, slide 2 ©c Raju Pandey

Basics

• (Nearly) everything (program and data) is represented by an

s-expression (symbolic expression).

Why? Programs could generate programs (AI motivation)

• Two kinds of s-exprs: Atoms and Lists.

• Atoms: Defines symbols and numbers.

  • Symbols: Denote names that can be bound to objects. Represented using identifiers

Example: A, CAR, B12, NIL, xyz

LISP does not distinguish between upper and lowercase

  • Numbers: integers and reals.

Example: 1, 2.3, 456

• nil represents false,and anything not nil represents true.

Note that nil represents both empty list and false. T also

used for representing true value.

• Lists: Constructed from atoms and lists. So programs and

data both represented as lists.

Representation: surround the elements of the list by ( and )

(): empty list

(1 2): list with 2 elements

(a (b c)): list with 2 elements

• LISP provides a number of functions for manipulating lists.

• Further, lists are nice vehicle for recursive programming.

Symbols and variables

• Symbols can be used to name variables, functions.

• They can be assigned values just like in other languages

• Symbols as variables:

(setq x 5) 5 (+ x 6) 11 (+ 2 (setq x (* 3 4))) 14 x 12

• symbols can also be assigned values through setf:

(setf glob 98) 98 (setf x (list ’a ’b ’c ’a)) (a b c a) (setf (car x) ’n) N x (N B C A) In the above example, value of a in list x is replaced by N: If the first argument of setf is an expression, the value of the

second argument is inserted in the place referred to by the first.

• Symbols as functions: functions such as +, -, setq are

denotes as symbols, except that they have a function value

• In LISP, same name can denote a variable and a function.

The two are treated differently:

(1+ 2) 3 (setq 1+ 5) (1+ 1+ 5) 10

List as a Data Structure

• Access various components of list through operations: car

and cdr.

car: return first element of list

cdr: return list consisting of remaining elements (tail)

Examples:

(car ’(a b c)) a (cdr ’(a b c)) (b c) (car (cdr ’(a b c))) b

• Construct lists: cons and list

cons: combine two entities (atoms and lists) to construct a

list:

(cons ’b nil) (b) (cons ’b (cons ’4 ’nil)) (b 4)

list: Constructs a list of of any length.

(list ’a ’b ’3 ’d) (a b 3 d) (list ’a (list ’b ’c) ’d) (a (b c) d)

• Special case of list where cdr is an atom:

(cons ’a ’b) (a.b) (list* ’a ’b ’c) = (a b.c)

• Many others: C....R, nth, append, nthcdr,

first, last, rest..

ECS140A, Winter’06 Common Lisp, slide 5 ©c Raju Pandey

How are lists represented internally?

• cons: an ordered conjunction of two elements.

Represented inside by a pair of storage elements, each of which can contain a reference to another lisp object. Fetch an unused node from memory, make the left pointer point to element, and right to list. Return pointer to full list.

(cons ’a (cons (cons ’c (cons ’d nil)) (cons ’b nil))) (A (C D) B)

• Represented using a binary tree. Lisp’s representation of list

(a (c d) b):

NIL a b

c d

• When a symbol is assigned a list, symbol points to the binary

tree representation of list.

• What does (car (a (c d) b)) return? LISP

interpreter returns pointer to the first element (it does not

copy).. Same with cdr

• Multiple pointer to same variable.

> (setq x ’(a b c))

(A B C)

> (setq y (cdr x))

(B C)

a (^) b c

NIL

x y

• Need to be careful about how you create lists and how you

share them.

ECS140A, Winter’06 Common Lisp, slide 6 ©c Raju Pandey

List as Programs

• When lists are represented as programs, LISP assigns

specific roles to different elements. Most of the trick (and initial frustration) is in understanding the roles of various elements.

• Rule 1: first element denotes a function and rest denote

arguments to function. So use prefix notation for specifying expressions (+ ’2 ’3) (cons ’b (cons ’4 ’nil))

• Rule 2: A function is applied by first evaluating the

arguments. So expression (f a1 a2 ... an) is

evaluated in the following manner: r1 = (eval a1); .. rn = (eval an); apply f on r1, r2, ..., rn Note that evaluation process is a recursive procedure.

• Meaning of evaluations of different kinds of argument:

– Number: evaluates to itself. 4 -> 4

– Symbol: evaluates to its value. Evaluation of a symbol x

may return 4 if value associated with x is 4.

  • List: evaluate list as an s-expression. (cons ’a (cons ’b nil))

Delay or Force Evaluation

• Lisp provides mechanisms for user control of blocking and

applying evaluations. (Source of major confusion and power)

• Used to change the default evaluation behavior of LISP.

• quote or ’ for overriding default evaluation:

(cons (quote a) (cons (quote b) nil)) (a b) (cons 3 ’(plus 5 6)) (3 plus 5 6) (cons a ’(b c)) (a1 b c)

a1: value resulting from evaluating a

• eval for specifically evaluating an expression:

(setq a (list ’+ 5 6)) (+ 5 6) (cons a ’(is the answer)) ((+ 5 6) is the answer) (cons (eval a) ’(is the answer)) (11 is the answer)

• Others: apply and funcall take function names and

apply over arguments.

apply: two arguments, function and list of arguments

funcall function and all of its arguments

(apply ’cons ’(a (b c))) (a b c) (apply ’+ ’(1 2 3 4 5 6)) 21 (apply ’* 2 3 ’(4 5 6)) 720 (funcall ’cons ’a ’(b c)) (a b c) (funcall ’member ’c ’(a b c d)) t

Control Constructs

Cond

• Similar to if-then-else of C++, Pascal etc.

(cond (b1 exp11 exp12 ...) ( ... ) ( bn expn1 expn2 .. ) )

b1, ..., bn are s-expressions returning a nil or

non-nil.

expij: s-expression

(b1 exp11 exp12 ...): clause

• Semantics: evaluate first element of first clause. If it returns

true, evaluate the corresponding expressions. If false, examine the next clause. Value returned: value of the last expression.

• Example

(cond ((atom x) (+ 2 3)) ((listp x) (+ 3 4)))

if

• Similar to if-then-else in conventional languages. Note

though that if here is an expression. It returns a value: (if test-form then-form else-form)

• Evaluate test-form, if non-nil, evaluate then-form

otherwise evaluate else-form. else-form is

optional. (if (numberp x) (+ x 1) 0)

ECS140A, Winter’06 Common Lisp, slide 13 ©c Raju Pandey

Control Constructs - cont’d.

Iteration

• Constructs for iteration: do

(do( (var-1 init-1 step-1) (var-2 init-2 step-2) ... (var-n init-n step-n)) ( end-test end-form-1 ... end-form-k return-value) body-1 body-2 ... body-m)

• Semantics:

1. var-1, var-2, ..., var-n: index variables.

They are created when do is executed. They persist for

the duration of do.

2. evaluate each init-i for var-i. This evaluates the

initial values for the index variables.

3. Evaluate end-test:

– non-nil: evaluate each end-form-i and

discard their value. Finally evaluate return-value

and return its value.

– nil: evaluate each body-i. if any expression of

form (return value) evaluated, do is exited, and

value returned as its value. if not, iteration is

complete.

Start next iteration by evaluating each step-i and

assigning the value to the corresponding index variable

var-i.

  • Continue with iteration as before.

ECS140A, Winter’06 Common Lisp, slide 14 ©c Raju Pandey

Iteration - cont’d.

• Example 1: length of a list

(defun length (x) (do((lst x (cdr lst)) (count 0 (+ 1 count))) ((null lst) count)))

lst, count: index variables.

- do does not have body here.

Recursive length:

(defun length (x)

(cond ((equal x nil) 0)

(t (+ 1 (length (cdr x))))))

• Example 2:

(defun get-longest (list1 list2) do ( (rem1 list1 (cdr rem1)) (rem1 list2 (cdr rem2)) (nil) (cond ((null rem1) (return list2)) ((null rem2) (return list1)))))

Note that do body makes sense only if it has side effects or

uses return.

• Example 3:

(let ((count 0)) (do ((I 3 (+ 1 I))) ((eql I 9) count) (setq count (+ 1 count)))) 6

Higher Order Functions

Mapping Functions

• A function is applied to all elements of a list.

• mapcar:

(mapcar func arglist-1 ... arglist-n)

• Semantics:

– func must take n arguments.

– Each application of func involves taking one argument

from each n list. The selection of the argument takes

place by first taking all cars, followed by cadrs and so

on..

  • Results of each application are collected in a list, and that list is returned.

• Example:

(mapcar ’+ ’( 1 2 3) ’(10 20 30)) (11 22 33) (mapcar ’sqr ’(1 2 3)) (1 4 9) (mapcar ’equal ’( 1 2 3) ’(1 3 a)) (t nil nil) (mapcar ’(lambda (N) (+ 1 N)) ’(5 3 6 7 2)) (6 4 7 8 3)

• mapc similar to mapcar except it always returns the

second argument as a value.

• maplist: apply a function to whole list given as an

argument to the mapping function, and then to successive cdrs:

(maplist ’cond ’(a b) ’(x y)) (((a b) x y) ((b) y))