Docsity

Functions, Recursion and Lists - Programming Languages | CS 3723, Study notes of Programming Languages

Partial preview of the text

Download Functions, Recursion and Lists - Programming Languages | CS 3723 and more Study notes Programming Languages in PDF only on Docsity!

Lisp

Functions, recursion and lists

The Lisp Programming

Language

 Stems from interest in symbolic computation  Led by John McCarthy in late 1950s  Designed for math logic in artificial intelligence  Functional programming paradigm  A program is a expression  Expresses flow of data; map input values to output values  No concept of control-flow or statements  No side effects or modification to variables  Functions are first-class objects  A function can be used everywhere a regular value is used  Functions can take other functions as parameters and return other functions as results (higher-order functions)  Adding side-effect operations  Different occurrences of expressions have different values  Strength and weakness  Simplicity and flexibility  Build prototype systems incrementally X Not many tools or libraries; Slow in speed/efficiency (interpreted)

Interacting with Scheme

(define pi 3.14159) ; bind pi to 3. (lambda (x) (* x x)) ; anonymous function (define sq (lambda (x) (* x x))) (define (sq x) (* x x)) ; (define sq (lambda (x) (* x x))) (sq 100) ; 100 * 100 (if P E1 E2) ; if P then E1 else E (cond (P1 E1) (P2 E2) (else E3)) ; (if P1 E1 (if P2 E2 E3)) (let ((x1 E1) (x2 E2)) E3) ; declare local variables x1 and x ((lambda (x1 x2) E3)) E1 E2) (let* ((x1 E2) (x2 E2)) E3) ; E2 can use x1 as a local variable (lambda (x1) ((lambda (x2) E3) E2) E1)

Expressions, Statements and

Declarations

 Expression (x+5)/  Syntactic entity that has a value  Need not change accessible memory  If it does, has a side effect  Statement load 4094 r  Imperative command  Alters the contents of previously-accessible memory  Declaration integer x  Introduces new identifiers (variables)  May bind value to identifier, specify type, etc.  Scoping rules for variables: which variable declaration does each identifier (name) refer to?

Lists in Lisp/Scheme

 In Lisp/Scheme, a list may contain arbitrary types of

values

 ‘(a b c) ‘(+ 2 (* 3 5)) ‘(lambda (a b) (cons a b))  A dynamically typed list can be used to implement most pointer- based data structures, including lists and trees.  Can it be used to implement arbitrary graphs? (can we build cycles in lists?)

 Lisp/Scheme lists can be used to naturally implement

AST --- a tree data structure used as an internal

representation of programs in compilers/interpreters

lambda +

/ \ / \

list cons 2 *

/ \ / \ / \

a b a b 3 5

Exercises

Programming in Lisp(Scheme)

 Programming steps  What are the input parameters? What values could each parameter take?  Enumerate each combination of input parameters, give a return value for each case  Exercise problems  Define a function Find which takes two parameters, x and y. It returns x if x appears in y, and returns an empty list (‘()) otherwise.  Define a function substitute which takes three parameters, x, y, and z. It returns a new list which replaces all occurrences x in y with z.  Define a function Max which takes a single parameter x, and returns the maximal number that appears in x.

Lisp: Adding Side Effects

 Pure Lisp  Expressions do not modify observable machine states  No side effects  Impure Lisp  Allow modifications to memory  May increase efficiency of programs  Eg. Modify a single element in a list  (set! x y)  Replace the value of x with y  (rplacea ’(A B) y) or (set-car! ’(A B) y)  replace A (the address field of ’(A B)) with y  (rplaced ’(A B) y) or (set-cdr! ’(A B) y)  replace B (the decrement field of ’(A B)) with y  Sequence operator  (progn (set! x y) x) or (begin (set! x y) x)  Set the value of x to be y; then returns the value of x

Functional Programming

 Functions are first-class objects  Functions treated same as primitive values (What about C/C++)?  Can be used to build anonymous and higher-order functions  Higher order functions are functions that either  Take other functions as arguments or return a function as result  First-order functions: parameters and results are not functions  Second-order functions: take as input or return first-order functions  Third-order functions: take as input or return second-order functions  Example: function composition (lambda (f g x) (f (g x))) vs. (lambda (f g) (lambda (x) (f (g x)))))

Return functions as results

 Function composition

(define compose

(lambda (f g) (lambda (x) (f (g x))))))

vs.

int compose(int (f)(...), int (g)(...), int x) { return f(g(x)); }  In Scheme  The function compose takes only two parameters  The result of compose is another function  in C  The function compose takes three parameters  The result of compose if a concrete value  C does not allow functions being returned as results, why?

Programming With Higher-order

Functions

 Apply a function to each element in a list (define maplist (lambda (f x) (cond ((null? x) nil) (else (cons (f (car x)) (maplist f (cdr x)))))))  Reduce a list into a single value (define reduce (lambda (f0 f1 f2 x) (cond ((null? x) f0) (else (f2 (f1 (car x)) (reduce f0 f1 f2 (cdr x)))))))  Increment each number in a list by 1 (define increment1 (lambda (x) (maplist (lambda (e) (if (number? e) (+ e 1) e)) x)))  Compute the sum of all numbers in a list (define sum (lambda (x) (reduce 0 (lambda (e) (if (number? e) e 0)) (lambda (res1 res2) (+ res1 res2)) x)))  Exercise:  A mapTree function that treat lists as trees  A mapTreePostOrder function that traverses a tree in post order

Implementing Lisp --- The Memory Model  Cons cells  Atoms and lists represented by cells Address Decrement Atom A Atom B Atom C

Sharing

 (a) (b)  Both structures could be printed as (A.B).(A.B)  Which are the results of evaluating  (cons (cons ‘A ‘B) (cons ‘A ‘B))?  ((lambda (x) (cons x x)) (cons ‘A ‘B))  Equality of compound structures  What is the result of (eq? ‘a ‘a)?  What is the result of (eq? ‘(a b) ‘(a b))?

A B A B

A B

Detecting Garbage

 Garbage  Memory locations in the heap that are no longer accessible  Examples (car (cons ( e 1 ) ( e 2 ) ))  Cells created in evaluation of e 2 may be garbage,  unless shared by e 1 or other parts of program ((lambda (x) (car (cons (… x…) (... x ...))) '(Big Mess))  The car and cdr of this cons cell may point to overlapping structures.  Need to keep track of how many active pointers are pointing to each store

Meta-programming

Programs As Data

 Meta programming languages  Computer programs can write or manipulate other programs (or themselves) as their data  If can modify themselves --- reflective programming  Lisp program can be represented using Lisp atoms and lists  Can be built/modified at runtime and then evaluated  An eval function used to evaluate contents of list  in Scheme, need to choose a more advanced language level (define atom? (lambda (x) (or (symbol? x) (number? x) (boolean? x)))) (define substitute (lambda (x y z) (cond ((null? z) z) ((atom? z) (if (eq? z x) y z)) (else (cons (substitute x y (car z)) (substitute x y (cdr z))))))) (define substitute-and-eval (lambda (x y z) (eval (substitute x y z)))) (substitute-and-eval ’x ’3 '(+ x 1))