43
1 Functional Programming with Scheme Read: Scott, Chapter 11.1-11.3

Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

1

Functional Programming with Scheme

Read: Scott, Chapter 11.1-11.3

Page 2: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 2

Lecture Outline

n Functional programming languagesn Scheme

n S-expressions and listsn cons, car, cdr

n Defining functionsn Examples of recursive functions

n Shallow vs. deep recursionn Equality testing

Page 3: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova 3

Racket/PLT Scheme/DrScheme

n Download Racket(was PLT Scheme (was DrScheme))n http://racket-lang.org/n Run DrRacketn Languages => Choose Language => Other

Languages => Legacy Languages: R5RSn One additional textbook/tutorial:

n Teach Yourself Scheme in Fixnum Days by DoraiSitaram:

https://ds26gte.github.io/tyscheme/index.html

Page 4: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova 4

First, Imperative Languages

n The concept of assignment is centraln X:=5; Y:=10; Z:=X+Y; W:=f(Z);

n Side effects on memoryn Program semantics (i.e., how the program

works): state-transition semanticsn A program is a sequence of assignment

statements with effect on memory (i.e., state)C := 0;for I := 1 step 1 until N dot := a[I]*b[I];C := C + t;

Page 5: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 5

Imperative Languages

n Functions (also called “procedures”, “subroutines”, or routines) have side effects:Roughly: n A function call affects visible state; i.e., a function

call may change state in a way that affects execution of other functions; in general, function call cannot be replaced by result

n Also, result of a function call depends on visible state; i.e., function call is not independent of the context of the call

Page 6: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

6

Imperative Languages

n Functions are, traditionally, not first-class valuesn A first-class value is one that can be passed as

argument to functions, and returned as result from functions

n In a language with assignments, it can be assigned into a variable or structure

n Are functions in C first-class values?n As languages become more multi-paradigm,

imperative languages increasingly support functions as first-class values (JS, R, Python, Java 8, C++11)

Page 7: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B.G. Ryder 7

Functional Languagesn Program semantics: reduction semantics

n A program is a set of function definitions and their application to arguments

Def IP = (Insert +) º (ApplyToAll *) º TransposeIP <<1,2,3>,<6,5,4>> is(Insert +) ((ApplyToAll *) (Transpose

<<1,2,3>,<6,5,4>>))(Insert +) ((ApplyToAll *) <<1,6>,<2,5>,<3,4>>)(Insert +) <6,10,12>28

Function composition

Page 8: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 8

Functional Languagesn In pure functional languages, there is no

notion of assignment, no notion of staten Variables are bound to values only through

parameter associationsn No side effects!

n Referential transparencyn Roughly:

n Result of function application is independent of context where the function application occurs; function application can be replaced by result

Page 9: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 9

Functional Languagesn Functions are first-class values

n Can be returned as value of a function application

n Can be passed as an argumentn In a language with assignment, can be assigned

into variables and structures

n Unnamed functions exist as values

Page 10: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 10

Lecture Outline

n Functional programming languagesn Scheme

n S-expressions and listsn cons, car, cdr

n Defining functionsn Examples of recursive functions

n Shallow vs. deep recursionn Equality testing

Page 11: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 11

Lisp and Schemen Lisp is the second oldest high-level programming

language!n Simple syntaxn Program code and data have same syntactic form

n The S-expressionn Function application written in prefix form

(e1 e2 e3 … ek) meansn Evaluate e1 to a function valuen Evaluate each of e2,…,ek to valuesn Apply the function to these values(+ 1 3) evaluates to 4

Page 12: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 12

History

Lisp1950’sJohn McCarthy

Scheme1975Guy SteeleGerald Sussman

Common Lisp

dynamic scoping lexical scopingfunctions as first-class values

Page 13: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Why Scheme?

n Simple syntax! Great to introduce core functional programming conceptsn Reduction semanticsn Lists and recursionn Higher order functionsn Evaluation ordern Parametric polymorphism

n Later we’ll see Haskell and new conceptsn Algebraic data types and pattern matchingn Lazy evaluationn Type inference 13

Page 14: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 14

S-expressions

S-expr ::= Name | Number | ( { S-expr } )

n Name is a symbolic constant (a string of chars which starts off with anything that can’t start a Number)

n Number is an integer or real numbern List of zero or more S-expr’sn E.g., (a (b c) (d)) is a list S-expr

a

bc ( )

d ( )( )

Page 15: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

15

List Functionsn car and cdr

n Given a list, they decompose it into first element, rest-of-list portions

n E.g., car of (a (b c) (d)) is an E.g., cdr of (a (b c) (d)) is ((b c)(d))

n consn Given an element and a list, cons builds a new list

with the element as its car and the list as its cdrn cons of a and (b) is (a b)

n () is the empty listProgramming Languages CSCI 4430, A. Milanova/B. G. Ryder

Page 16: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

16

Quotingn ‘ or quote prevents the Scheme interpreter from evaluating the argument

(quote (+ 3 4)) yields (+ 3 4)

‘(+ 3 4) yields (+ 3 4)

Whereas (+ 3 4) yields 7

n Why do we need quote?Programming Languages CSCI 4430, A. Milanova/B. G. Ryder

Page 17: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Questions(car ‘(a b c)) yields ?(car ‘((a) b (c d))) yields ? (cdr ‘(a b c)) yields ?(cdr ‘((a) b (c d))) yields ?

Can compose these operators in a short-hand manner. Canreach arbitrary list element by composition of car’s and cdr’s.(car (cdr (cdr ‘((a) b (c d)) )))

can also be written (caddr ‘((a) b (c d)) )(car (cdr (cdr ‘((a) b (c d)) ))) = (car (cdr ‘( b (c d))) = (car ‘((c d))) = (c d)

a ()

b

c d () ()

((a) b (c d))

Page 18: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

18

Questions

n Recall consn E.g., (cons ‘a ‘(b c)) yields (a b c)

(cons ‘d ‘(e)) yields ?(cons ‘(a b) ‘(c d)) yields ?(cons ‘(a b c) ‘((a) b (c d))) yields ?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder

Page 19: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

19

Type Predicatesn Note the quote: it prevents evaluation of the

argument (symbol? ‘sam) yields #t (symbol? 1) yields #f(number? ‘sam) yields #f (number? 1) yields #t(list? ‘(a b)) yields #t (list? ‘a) yields #f(null? ‘()) yields #t (null? ‘(a b)) yields #f(zero? 0) yields #t (zero? 1) yields #f

Can compose these.(zero? (- 3 3)) yields #t Note that since thislanguage is fully parenthesized, there are no precedenceproblems in expressions!

Page 20: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Question

n What is the typing discipline in Scheme?n Static or dynamic?

n Answer: Dynamic typing. Variables are bound to values of different types at runtime. All type checking done at runtime.

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 20

Page 21: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 21

Lecture Outline

n Functional Programming Languagesn Scheme

n S-expressions and listsn cons, car, cdr

n Defining functionsn Examples of recursive functions

n Shallow vs. deep recursionn Equality testing

Page 22: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 22

Scheme: Defining Funcitons

Fcn-def ::= (define (Fcn-name {Param}) S-expr)Fcn-name should be a new name for a function.Param should be variable(s) that appear in the S-expr which is the function body.

Fcn-def ::= (define Fcn-name Fcn-value)Fcn-value ::= (lambda ( {Param} ) S-expr)where Param variables are expected to appear in the

S-expr; called a lambda expression.

Page 23: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

23

Examples

(define (zerocheck? x) (if (= x 0) #t #f) )

If-expr ::= ( if S-expr0 S-expr1 S-expr2 )where S-expr0 must evaluate to a boolean value; if that value is #t, then the If-expr yields the result of S-expr1, otherwise it yields the result of S-expr2.

(zerocheck? 1) yields #f, (zerocheck? (* 1 0)) yields #t

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder

Page 24: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 24

Examples

(define (atom? object) (not (pair? object)) )

Here pair? is a built-in type predicate. It yields #tif the argument is a non-trivial S-expr (i.e., something one can take the cdr of). It yields #f otherwise.

not is the built-in logical operator.

What does atom? do?

Page 25: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 25

Examples

(define square (lambda (n) (* n n)))

n Associates the Fcn-name square with the function value (lambda (n) (* n n))

n Lambda calculus is a formal theory of functions n Set of functions definable using lambda calculus (Church

1941) is same as set of functions computable as Turing Machines (Turing 1930’s)

Page 26: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

26

Trace of Evaluation(define (atom? object) (not (pair? object)) )

(atom? `(a))-obtain function value corresponding to atom?-evaluate `(a) obtaining (a)-evaluate (not (pair? ‘(a)))

-obtain function value corresponding to not-evaluate (pair? ‘(a))

-obtain function value corresponding to pair?-evaluate ‘(a) obtaining (a)-return value #t

-return #f-return #f

Page 27: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

27

Read-Eval-Print Loop (REPL)n Scheme interpreter runs read-eval-print loop

n Read input from usern A function application

n Evaluate inputn (e1 e2 e3 … ek)

n Evaluate e1 to obtain a functionn Evaluate e2, … , ek to valuesn Execute function body using values from previous step as

parameter valuesn Return value

n Print return value

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder

Page 28: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

28Programming Languages CSCI 4430, A. Milanova/B. G. Ryder

Page 29: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 29

Conditional Execution

(if e1 e2 e3)(cond (e1 h1) (e2 h2) … (en-1 hn-1) (else hn))

n Cond is like if – then – else if construct

(define (zerocheck? x) (cond ((= x 0) #t) (else #f)))

OR(define (zchk? x)(cond ((number? x) (zero? x))

(else #f)))

Page 30: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

30

Recursive Functions(define (len x) (cond ((null? x) 0) (else (+ 1 (len (cdr x))))))

(len `(1 2)) should yield 2.Trace:(len `(1 2)) -- top level call

x = (1 2)(len `(2)) -- recursive call 1x = (2)

(len `()) -- recursive call 2x = ()returns 0 -- return for call 2

returns (+ 1 0) = 1 --return for call 1returns (+ 1 1) = 2 -- return for top level call

(len ‘((a) b (c d))) yields what?

len is a shallow recursive function

Page 31: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 31

Recursive Functions(define (app x y)(cond ((null? x) y)

((null? y) x)(else (cons (car x)

(app (cdr x) y)))))

n What does app do?

(app ‘() ‘()) yields ?(app ‘() ‘(1 4 5)) yields ?(app ‘(5 9) ‘(a (4) 6)) yields ?

app is a shallow recursive function

Page 32: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

32

Exercise(define (len x) (cond ((null? x) 0) (else (+ 1 (len (cdr x))))))

Write a version of len that uses if instead of cond

Write a function countlists that counts the numberof list elements in a list. E.g.,

(countlists ‘(a)) yields 0(countlists ‘(a (b c (d)) (e))) yields 2

Recall (list? l) returns true if l is a list, false otherwise

Page 33: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 33

Recursive Functions(define (fun x)(cond ((null? x) 0)

((atom? x) 1)(else (+ (fun (car x))

(fun (cdr x)))) ))

fun is a deep recursive function

What does fun do?

Page 34: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 34

fun counts atoms in a list(define (atomcount x)

(cond ((null? x) 0)((atom? x) 1)(else (+ (atomcount (car x)) (atomcount (cdr x)))) ))

(atomcount ‘(a)) yields 1(atomcount ‘(1 (2 (3)) (5)) ) yields 4

Trace: (atomcount ‘(1 (2 (3)) )1> (+ (atomcount 1) (atomcount ‘( (2 (3)) ) ))

2> (+ (atomcount ‘(2 (3)) ) (atomcount ‘( ) ) )3> (+ (atomcount 2) (atomcount ‘((3)) )

4> (+ (atomcount ‘(3)) (atomcount ‘( )) )5> (+ (atomcount 3) (atomcount ‘( )))

01

atomcount is a deep recursive function

Page 35: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 35

Exercise

n Write a function flatten that flattens a list

(flatten ‘(1 (2 (3)))) yields (1 2 3)

Page 36: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 36

Lecture Outline

n Functional Programming Languagesn Scheme

n S-expressions and listsn cons, car, cdr

n Defining functionsn Examples of recursive functions

n Shallow vs. deep recursionn Equality testing

Page 37: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

37

Equality Testingeq?

n Built-in predicate that can check atoms for equal valuesn Does not work on lists in the way you might expect!

eql?n Our predicate that works on lists(define (eql? x y)(or (and (atom? x) (atom? y) (eq? x y))

(and (not (atom? x)) (not (atom? y))(eql? (car x) (car y))(eql? (cdr x) (cdr y)) )))

equal?n Built-in predicate that works on lists

Page 38: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 38

Examples(eql? ‘(a) ‘(a)) yields what?(eql? ‘a ‘b) yields what?(eql? ‘b ‘b) yields what?(eql? ‘((a)) ‘(a)) yields what?

(eq? ‘a ‘a) yields what?(eq? ‘(a) ‘(a)) yields what?

Page 39: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova 39

Models for Variables

n Value model for variablesn A variable is a location that holds a value

n I.e., a named container for a valuen a := b

n Reference model for variablesn A variable is a reference to a valuen Every variable is an l-value

n Requires dereference when r-value needed (usually, but not always implicit)

l-value (the location) r-value (the value held in that location)

Page 40: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 40

Models for Variables: Example

n Value model for variablesn b := 2 b: n c := b c: n a := b+c a:

n Reference model for variablesn b := 2 bn c := b cn a := b+c a

b := 2;

c := b;

a := b + c;2

2

4

2

4

Page 41: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Programming Languages CSCI 4430, A. Milanova/B. G. Ryder 41

Equality Testing: How does eq? work?n Scheme uses the reference model for variables!

(define (f x y) (list x y))

Call (f ‘a ‘a) yields (a a)x refers to atom a and y refers to atom a.eq? checks that x and y both point to the

same place.

Call (f ‘(a) ‘(a)) yields (‘(a) ‘(a))x and y do not refer to the same list.

x

ya

x

y

( )a

A cons cell

Page 42: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

Models for Variables

n C/C++, Pascal, Fortrann Value model

n Javan Mixed model: value model for simple types,

reference model for class typesn JS, Python, R, etc.

n Reference model n Scheme

n Reference model! eq? is “reference equality” (akin of Java’s ==), equal? is value equality

42

Page 43: Functional Programming with Schememilanova/csci4430/Lecture12.pdf1975 Guy Steele Gerald Sussman Common Lisp dynamic scoping lexical scoping functions as first-class values Why Scheme?

The End

Programming Languages CSCI 4430, A. Milanova 43