Professional Documents
Culture Documents
Outline
Functional versus Procedural approach. The Von Neumann bottleneck. Introduction to Scheme. Recursion. Modeling data structures.
CS 454
3-2
Bench Algorithm
1. 2. 3. 4. 5. 6.
Plane what you have in your hands and leave it on your right. Take what is on your left. Put before you what you have in your hands. Repeat steps 3 & 4 three more times. Mount what you have on your right on top of what is before you.
Copyright 1990-2013 James M. Bieman 3-4
A pole on Fridays left side. A plank on Fridays right side. And gives the following directions:
CS 454 Copyright 1990-2013 James M. Bieman 3-3
CS 454
Observation
Poor Friday!
He doesnt dare change the sequence or placement of items. Even a second Friday is no help.
Poor Robinson!
He had to perform the construction in his mind to write the algorithm. What if he forgot something?
3-5
Prescribes activity in terms of how to do it rather than what and why. Prescribes activity in terms of the system that executes it rather than in the activities own terms. Rigid sequence of commands; action driven. Actions tightly coupled to system space. Cyclic --- requires careful planning.
Copyright 1990-2013 James M. Bieman 3-6
CS 454
CS 454
CS 454: Principles of Programming Languages Notes 3: Intro. To Functional Programming and Scheme
Bench Making
Bench(Plank,Pole)=
Mount(Plane(Saw(Plank)), Cut-four-pieces(Pole))
Output = Function(inputs).
Bench = Mount(Seat, Legs). Legs = Cut-four-pieces(Pole).
Visualize as a tree:
Mount Plane Saw Plank Pole Cut-four-pieces
Bench(Plank,Pole)=
Observation:
Parallelism is apparent:
You do the seat; I do the legs.
3-8
CPU
Memory
CS 454
3-9
CS 454
3-10
Several assignment statements, each with one word results. Assignments executed many times to make desired overall change in memory. Programmer is concerned with the flow of words through an assignment bottleneck when designing a program. Assignment statement
= VN bottleneck = intellectual bottleneck
CS 454
3-12
CS 454: Principles of Programming Languages Notes 3: Intro. To Functional Programming and Scheme
Functional Programming
No assignments (in pure functional languages). Small concise framework. Simpler syntax (usually). Mathematically easier to handle.
LISP: LISt Processing language. 1958-1959: developed by John McCarthy and his students at MIT. To prove the equivalence of Lisp to Turing machines, McCarthy wrote a Lisp function that simulates Lisp functions. Steve Russell hand compiled McCarthys theoretical function, the apply or eval function. Lisp evolved into an extensive language of many flavors. Common Lisp is popular in the field of Artificial Intelligence. 1970s: Guy Steele and Gerald Sussman developed Scheme as a small, clean functional programming language. 2010: Scheme evolves into Racket.
Copyright 1990-2013 James M. Bieman 3-14
CS 454
3-13
CS 454
Lisp/Scheme Characteristics
Lisp/Scheme Applications
Non-numeric processing (performance improvements support numeric applications). Artificial intelligence: due to interactive nature, lack of static type checking, higher order nature, and storage management. Programming language theory: due to simple syntax, higher order and applicative nature. We concentrate on Scheme without assignments and variables.
Lists are fundamental data types; lists can hold lists. Interactive. Simple syntax: programs & data appear the same and are lists. No compile-time type checking. Higher-order: functions can take functions as arguments and return functions.
Storage management: heap based; automatic deallocation via garbage collection. Original Lisp used dynamic scoping identifiers attached to most recent definition.
Common Lisp and Scheme use static scoping (similar to C and Java).
CS 454
3-15
Scheme
Statically scoped: each use of a variable is associated with a lexically apparent binding of that variable. Dynamically typed: types are associated with values rather than with variables. All objects in the course of a Scheme computation have unlimited extent:
Factorial in Scheme
(define fact (lambda (n) (if (= n 0) 1 (* n (fact (- n 1))) ) )) Fully parenthesized prefix notation for programs and data.
CS 454 Copyright 1990-2013 James M. Bieman 3-18
Procedures/functions can be created dynamically, stored in data structures, returned as results of functions, etc.
Copyright 1990-2013 James M. Bieman 3-17
CS 454
CS 454: Principles of Programming Languages Notes 3: Intro. To Functional Programming and Scheme
Conventions
Identifiers
Predicates: functions that always return a boolean. State changing procedures --- those that store values into previously allocated locations. Functions that take an object of one type and return an object of another type: Upper and lower case letters are not distinguished in names. (They are in constants.)
-> appears within the function name. Procedure names usually end with a !. Function names usually end with a ?.
Start with a character or special character, followed by a sequence of special characters, or digits: Syntactic structure:
Foo, lambda, list->vector, +, myName, big-deal, x27, x. <identifier> ::= <initial> <subsequent>* | <peculiar identifier> <initial> ::= <letter> | <special initial> <special initial> ::= ! | $ | % | & | * | / | : | < | = | > | ? | ^ | _ | ~ <subsequent> ::= <initial> | <digit> | <special subsequent> <special subsequent> ::= + | - | . | @ <peculiar identifier> ::= + | - |
Copyright 1990-2013 James M. Bieman 3-20
CS 454
3-19
CS 454
Predicates
Variables may name a syntax element, or a location where a value can be stored.
True: #t
Location names: variable that is bound to that location. Syntax names: syntactic keyword that is bound to that syntax. The binding of an identifier corresponds to a region of the program text where the binding is visible.
Copyright 1990-2013 James M. Bieman 3-21
False: #f. Type predicates. No object satisfies more than one of the following predicates: The empty list, (), is a special object of its own type; it satisfies only list?.
boolean?, symbol?, char?, vector?, procedure?, pair?, number?, string?, port?
CS 454
CS 454
3-22
Literal Expressions
Either external representations of scheme objects or constants that evaluate to themselves: Syntax: (quote <datum> | `<datum> | constant ) Examples:
Function/Procedure Calls
Enclose the function/procedure name and arguments in quotes Syntax: (<operator> {<operand>}* ) Examples:
> > (+ 2 3) 5 > (+ 2 3 4) 9 > ((if #f + *) 3 4) 12
> (quote a) ; evaluates to <datum> a > (quote (+ 1 2)) ; evaluates to (+ 1 2) (+ 1 2) > `(+ 1 2) ; abbreviation of (quote (+ 1 2)) (+ 1 2) > string ; evaluates to itself; quote is not needed. string
Copyright 1990-2013 James M. Bieman 3-23
Uses call-by-value: each argument is evaluated, including the expression denoting the function, before the function is invoked.
CS 454 Copyright 1990-2013 James M. Bieman 3-24
CS 454
CS 454: Principles of Programming Languages Notes 3: Intro. To Functional Programming and Scheme
Functions/Procedures
Functions are parameterized abstractions over expressions. Syntax: (lambda <formals> <body>)
<formals> a formal parameter list.
<formals> ::= ({<variable>}+ ) | <variable> | ( <variable1> <variableN> . <variableN+1>)
Syntax:
( define <variable> <expression>)
Examples:
<body> is a sequence of one or more expressions. > ((lambda (x) (+ x x)) 4) 8 > ((lambda x x) 3 4 5 6) (3 4 5 6) > ((lambda (x y . z) z) 3 4 5 6) (5 6)
Examples:
> (define succ (lambda (x) (+ x 1))) > (succ 7) 8 > (define square (lambda (x) (* x x))) > (square 5) 25
CS 454
3-25
CS 454
3-26
Conditionals
(if <test> <consequent> <alternative>) (if <test> <consequent>) (cond <clause1> <clause2> )
Each clause is of the form:
(<test> <expression1> ) or (<test> => <expression>)
Pairs represent lists. A list is either an empty list or a pair whose cdr is a list:
(a b c d e) and (a . (b . (c . (d . (e . ()))))) mean the same thing.
CS 454
3-28
Operations on Lists
(pair? (a . B)) #t (pair? (a b c)) #t ; a list is a pair: (a . (b . (c . ()))) (pair? ()) #f; the empty list is not a pair.
(car pair) returns the contents of the car field of the pair the 1st element of a list:
(car (1 2 3)) 1 (car ((a) b c)) (a) (car ()) error; () has no car field.
(null? obj) returns #t if obj is the empty list, otherwise returns #f. (list? obj) returns #t if obj is a list, #f otherwise.
Copyright 1990-2013 James M. Bieman 3-29
(cdr pair) returns the contents of the cdr field of pair the list without the 1st element.
(cdr (1 2 3)) (2 3) (cdr ((a) b c)) (b c) (cdr (a . b)) b (cdr ()) error; () has no cdr field.
CS 454
CS 454
3-30
CS 454: Principles of Programming Languages Notes 3: Intro. To Functional Programming and Scheme
Abbreviations
(caar L) (car (car L)) (cdar L) (cdr (car L)) (cadar L) (car (cdr (car L))) (caddar L) (car (cdr (cdr (car L))))
(cadar ((a b c d) e)) c (cadar ((a b) c)) b (cdar ((a b) c)) (b) (caar ((a b) c)) a
(cons obj1 obj2) returns a newly allocated pair whose car is obj1 and cdr is obj2.
(cons a ()) (a) (cons (a) (b c)) ((a) b c) (cons (a b) (c d)) ((a b) c d) ( car (cons (a) (b c))) (a)
CS 454
3-32
(append list1 list2 listN) returns a new list containing the elements of the first list followed by the elements of the other lists.
(append (a) (b)) (a b) (append (a) (b c)) (a b c) (append (a (b)) ((c)) (a (b) (c))
CS 454
3-33
CS 454
3-34
Vectors
Vectors are lists in which each element has an index and can be accessed through the index To create a vector, use the vector procedure
=>(vector 6 7 8) #3(6 7 8)
#3 means this is a vector with 3 elements
CS 454 Copyright 1990-2013 James M. Bieman 3-35
CS 454
3-36
CS 454: Principles of Programming Languages Notes 3: Intro. To Functional Programming and Scheme
Map
Equivalence Predicates
(map F L)
Maps a unary function F onto list L. F is invoked on each item in L and map returns the list of the results.
(map F L1 L2 ...)
(eqv? obj1 obj2) returns #t if obj1 and obj2 should normally be regarded as the same object. Very similar to eq?
(eqv? #t #t) #t
Maps a function F with arity n onto n lists of operands. Call F once for each item in L1, L2, The 1st time, F processes 1st element of each list, then it processes the 2nd element of each list, etc. > (map + '(1 2 3) '(2 3 4) '(3 4 5)) (6 9 12)
(equal? obj1 obj2) structural equivalence like the equals method in Java. Recursively compares the contents of lists, pairs, etc using eqv? on primitives.
(equal? (a b) (a b)) #t (equal? (cons a ()) (cons a ())) #t
CS 454
3-37
CS 454
3-38
Expression Evaluation
Implications
A list is a function call. The value of a list is a function call. But the value of (a b c) or (quote (a b c)) is the list (a b c) and not a call to the function a. () need not be quoted. #t, #f, and numbers need not be quoted.
CS 454 Copyright 1990-2013 James M. Bieman 3-40
(eval L) algorithm:
Note that quote, i.e. (a b) is a special function that returns its arg unevaluated.
Copyright 1990-2013 James M. Bieman
if L is a primitive then return Ls value else if (car L) names a normal function then in order eval each arg in L and apply (car L) using the evaluated args else if (car L) names a special function that does not eval its args then apply (car L) with unevaluated args else error.
CS 454
3-39
Some Functions
Factorial Revisited
(define fact (lambda (n) (if (= n 0) 1 (* n (fact (- n 1)))))) Try it: (fact 3)
(if (= 3 0) 1 (* 3 (fact (- 3 1)))) (if #f 1 (* 3 (fact (- 3 1)))) (* 3 (fact (- 3 1))) (* 3 (fact 2))) (* 3 (if (= 2 0) 1 (* 2 (fact (- 2 1))))) (* 3 (if #f 1 (* 2 (fact (- 2 1))))) (* 3 (* 2 (fact (- 2 1)))) (* 3 (* 2 (fact 1))) (* 3 (* 2 (if (= 1 0) 1 (* 1 (fact (- 1 1)))))) (* 3 (* 2 (if #f 1 (* 1 (fact (- 1 1)))))) (* 3 (* 2 (* 1 (fact (- 1 1))))) (* 3 (* 2 (* 1 (fact 0)))) (* 3 (* 2 (* 1 (if (= 0 0) 1 (* 0 (fact (- 0 1)))))) (* 3 (* 2 (* 1 (if #t 1 (* 0 (fact (- 0 1))))))) (* 3 (* 2 (* 1 1))) Copyright 1990-2013 James M. Bieman
(define double (lambda (N) (+ N N))) (define double2 (lambda (M N) (+ (double M) (double N)))) Lets use the functions:
(+ (double 3) (double2 4 6)) (+ (+ 3 3) (double2 4 6)) (+ 6 (double2 4 6)) (+ 6 (+ (double 4) (double 6))) (+ 6 (+ (+ 4 4) (double 6))) (+ 6 (+ 8 (double 6))) (+ 6 (+ 8 (+ 6 6))) (+ 6 (+ 8 12)) (+ 6 20) 26
Winding phase
CS 454
3-41
CS 454
3-42
CS 454: Principles of Programming Languages Notes 3: Intro. To Functional Programming and Scheme
Factorial Continued
(* 3 (* 2 (* 1 1)))
(* 3 (* 2 1))) (* 3 2 ) 6
Unwinding phase
Run it:
CS 454
3-43
CS 454
Returning a List
Unwind doubleAll
(cons 2 (cons 4 (cons 6 () ))) (cons 2 (cons 4 (6) )) (cons 2 (4 6) ) (2 4 6)
(define doubleAll (lambda (L) (if (null? L) () (cons (* (car L) 2) (doubleAll (cdr L)))))) Run it: (doubleAll (1 2 3)) (cons (* 1 2) (doubleAll (cdr (1 2 3)) (cons 2 (doubleAll (2 3))) (cons 2 (cons (* 2 2) (doubleAll (cdr (2 3))))) (cons 2 (cons 4 (doubleAll (3)))) (cons 2 (cons 4 (cons (* 3 2) (doubleAll () )))) (cons 2 (cons 4 (cons 6 (doubleAll () )))) (cons 2 (cons 4 (cons 6 () )))
Copyright 1990-2013 James M. Bieman 3-45
CS 454
CS 454
3-46
For mylength:
V0 is 0. OPH: is a constant function that converts the head element into a 1. OPC: +
For doubleAll:
V0 is (). OPH is (* head 2). OPC is cons.
CS 454
3-48
CS 454: Principles of Programming Languages Notes 3: Intro. To Functional Programming and Scheme
constList
(define constList (lambda (V L) (if (null? L) () (cons V (constList V (cdr L)))))) Builds an answer list that is the same length as L, but each element in the answer list is the value V. Uses recursion on its second argument list L.
First argument is carried along at each function call and copied into the answer list as needed.
Copyright 1990-2013 James M. Bieman
L is shortened by one element before each recursive call to guarantee termination, when L is empty.
CS 454
3-50
myAppend
(define myAppend (lambda (L1 L2) (if (null? L1) L2 (cons (car L1) (myAppend (cdr L1) L2) ))))
Reverse a List
(define myReverse (lambda (L) (myRev L '()))) (define myRev (lambda (arg ans) (if (null? arg) ans (myRev (cdr arg) (cons (car arg) ans)))))
CS 454 Copyright 1990-2013 James M. Bieman 3-52
Builds an answer list that is the concatenation of its two argument lists L1 and L2. The 1st list is decomposed. The 1st element in L1 is inserted into the answer produced by the recursive call. The recursive call appends a shortened L1 into L2. Its is much easier to decompose the 1st list than the 2nd.
The program terminates when L1 becomes empty.
CS 454
3-51
(myReverse (1 (a b) 3))
(myRev (1 (a b) 3) ()) (myRev ((a b) 3) (1)) (myRev (3) ((a b) 1)) (myRev () (3 (a b) 1)) (3 (a b) 1)
Answer built in the 2nd argument to myRev. When the 1st argument is an empty list, the 2nd argument holds the answer. myReverse initializes myRev with the proper ans argument for reversing an empty list. At each recursive call, the 1st argument is smaller. No unwinding stage!
CS 454
3-53
CS 454
3-54
CS 454: Principles of Programming Languages Notes 3: Intro. To Functional Programming and Scheme
(define startFun (lambda (L) (Fun L v0))) (define Fun (lambda (L ans) (if (null? L) ans (Fun (cdr L) (opH2ans (opH (car L)) ans))))
V0: answer for an empty list. opH: processes head element of list. opH2ans: combines the answer from the head element with the partial answer value (ans) produced so far.
Copyright 1990-2013 James M. Bieman 3-55
CS 454
CS 454
Non-tail recursive functions can be written in iterative form (in C or Java) without recursion.
Use a stack data structure to simulate recursion.
Why?
CS 454
3-57
CS 454
3-58
Modeling Trees
Binary tree: v0 v1 v3 v4 v2 v5 v6
Modeled by:
(v0 (v1 (v3 ()) (v4 ())) (v2 (v5 (..)) (v6 ())) )
CS 454 Copyright 1990-2013 James M. Bieman 3-59 CS 454
Relation between node v & its subtrees takes the form: (v T1 T2). Useful ops: build empty tree, build tree from root & subtrees, traverse a tree, list values attached to nodes.
3-60
CS 454: Principles of Programming Languages Notes 3: Intro. To Functional Programming and Scheme
Summary
The functional approach to programming. Introduction to Scheme:
Constructs. Programming.
CS 454