Scheme Tutorial - PowerPoint PPT Presentation

1 / 90
About This Presentation
Title:

Scheme Tutorial

Description:

(make-rect ( (real-part z1) (real-part z2)) ( (imag-part z1) (imag-part z2) ... (define (make-rect x y) (cons (sqrt ( (square x) (square y))) (atan y x) ... – PowerPoint PPT presentation

Number of Views:114
Avg rating:3.0/5.0
Slides: 91
Provided by: acer175
Category:
Tags: rect | scheme | tutorial

less

Transcript and Presenter's Notes

Title: Scheme Tutorial


1
Scheme Tutorial
2
Goals
  • Combine several simple ideas into one compound
    idea to obtain complex ideas
  • Bring two ideas together to obtain relations
  • Seperate ideas from all other ideas that
    accompany them in real existence to obtain
    general ideas (this is called abstraction)
  • by John Locke, An Essay Concerning Human
    Understanding (1690)

3
Features of LISP
  • Recursive Functions of Symbolic Expressions and
    Their Computation by Machine (John McCarthy,
    1960)
  • LISP stands for LISt Processing
  • An interpreted language (not efficient)
  • Second oldest language (after FORTRAN)
  • Designed to solve problems in the form of
  • symbolic differentiation integration of
    algebraic expressions

4
Features of LISP
  • LISPs ability
  • to represent procedures as data
  • to manipulate programs as data
  • LISP is currently a family of dialects (share
    most of the original features)
  • Scheme is a dialect of LISP (small yet powerful)

5
Characteristics of SCHEME
  • Supports functional programming - but not on an
    exclusive basis
  • Functions are first class data objects
  • Uses static binding of free names in procedures
    and functions
  • Types are checked and handled at run time - no
    static type checking
  • Parameters are evaluated before being passed - no
    lazyness

6
Elements of Language
  • Primitive expressions simple expressions
  • Means of combination compound expressions
  • Means of abstraction compound objects can be
    named and manipulated as units

7
Scheme Expressions - 1
  • gt 395
  • 395
  • gt ( 137 349)
  • 486
  • gt (/ 10 6)
  • 1.66667

8
Scheme Expressions - 2
  • Prefix Notation
  • take arbitrary number of arguments
  • gt ( 21 35 12 7)
  • 75
  • gt ( 25 4 12)
  • 1200

9
Scheme Expressions - 3
  • Prefix Notation
  • allow combinations to be nested
  • gt ( ( 3 5) (- 10 6) )
  • 19
  • gt ( ( 3 (- ( 2 1) 5) (/ 4 2)) ( 3 2))
  • Read Eval Print loop

10
Scheme Pretty-Printing
  • gt ( ( 3 ( ( 2 4) ( 3 5))) ( (- 10 7) 6))
  • ( ( 3
  • ( ( 2 4)
  • ( 3 5)))
  • ( (- 10 7)
  • 6))
  • gt (load e1.scm)

11
Scheme Naming
  • gt (define size 2)
  • gt size
  • 2
  • gt ( 5 size)
  • 10
  • gt (load e2.scm)

12
Compound Procedures
  • gt (define (square x) ( x x))
  • gt (square 3)
  • 9
  • (define (lt name gt lt formal parameters gt) lt body gt
    )
  • gt (load e3.scm)
  • Substitution model for procedure application

13
Conditional Expressions
  • gt (define (abs x)
  • (cond ((gt x 0) x)
  • (( x 0) 0)
  • ((lt x 0) (- x))))
  • gt (define (abs x)
  • (cond ((lt x 0) (- x))
  • (else x)))

14
Conditional Expressions
(cond (ltp1gt lte1gt) (ltp2gt lte2gt)
(ltpNgt lteNgt)) p is predicate either
true (non-nil) or
false (nil) e is consequent
expression returns the value of it
15
Conditional Expressions
  • gt (define (abs x)
  • (if (lt x 0)
  • (- x)
  • x))
  • (if ltpredicategt ltconsequentgt ltalternativegt)

16
Logical Operators
  • Primitive operators lt , gt ,
  • Logical operators and , or , not
  • gt (define (gt x y)
  • (or (gt x y) ( x y)))
  • Example another definition of (gt x y)
  • Example 5 lt x lt 10

17
Procedures
  • different than mathematical functions
  • ?x the y such that y ? 0 and y2 x
  • gt (define (sqrt x)
  • (the y (and (gt y 0) ( (square y) x))))
  • Mathematics declarative (what is)
  • Programs imperative (how to)
  • Square Roots by Newtons Method
  • gt (load e4.scm) - ?2 1.4142...

18
Square Roots by Newtons Method
  • break the problem into subproblems
  • how to tell whether a guess is good enough
  • how to improve a guess
  • how to calculate the average of two numbers
  • etc.
  • each of the above tasks is a procedure

19
Square Roots by Newtons Method
sqrt
sqrt-iter
good-enough?
improve
square
abs
average
gt (load e4.scm)
20
Procedures Black Box Abstractions
  • (define (square x)
  • ( x x))
  • (define (square x)
  • (exp ( (log x) (log x))))

21
Procedural Abstractions
  • (define (square x) ( x x))
  • (define (square y) ( y y))
  • (define (square variable) ( variable variable))
  • parameter names that are local to the procedure
  • bound variables change throughout the
    procedure does not change the meaning of the
    procedure
  • free variables if a variable is not bound in
    the proc
  • (define (good-enough? guess x)
  • (lt (abs (- (square guess) x)) .001))

22
Internal Definitions
  • Encapsulation hiding details
  • gt (load e4.scm)
  • Nesting definitions block structure
  • gt (load e5.scm)
  • Lexical scoping not necessary to pass x
    explicitly to internal procedures, so x becomes
    free variable in the internal definitions
  • gt (load e6.scm)

23
Procedures
  • Procedure
  • a pattern for the local evolution of
  • a computational process.
  • At each step,
  • the next state of the process is computed from
  • its current state according to the rules of
  • interpreting procedures.

24
Linear Recursion
  • (factorial 6)
  • ( 6 (factorial 5))
  • ( 6 ( 5 (factorial 4)))
  • ( 6 ( 5 ( 4 (factorial 3))))
  • ( 6 ( 5 ( 4 ( 3 (factorial 2)))))
  • ( 6 ( 5 ( 4 ( 3 ( 2 (factorial 1))))))
  • ( 6 ( 5 ( 4 ( 3 ( 2 1)))))
  • ( 6 ( 5 ( 4 ( 3 2))))
  • ( 6 ( 5 ( 4 6)))
  • ( 6 ( 5 24))
  • ( 6 120)
  • 720

process does grow and shrink
25
Linear Recursion
  • n! n (n-1) (n-2) ... 2 1
  • n! n (n-1)!
  • n! n ( (n-1) (n-2)! )
  • n! n ( ... ( (n-1) (n-2) ... 1! ) ) ...
    )
  • (define (factorial n)
  • (if ( n 1)
  • 1
  • ( n (factorial (- n 1)))))

26
Linear Iteration
  • (factorial 6)
  • (fact-iter 1 1 6)
  • (fact-iter 1 2 6)
  • (fact-iter 2 3 6)
  • (fact-iter 6 4 6)
  • (fact-iter 24 5 6)
  • (fact-iter 120 6 6)
  • (fact-iter 720 7 6)
  • 720

process does not grow and shrink
27
Linear Iteration
  • Product, counter 1
  • do while counter lt n
  • product counter product
  • counter counter 1
  • (define (factorial n)
  • (fact-iter 1 1 n))
  • (define (fact-iter product counter max-count)
  • (if (gt counter max-count)
  • product
  • (fact-iter ( counter product)
  • ( counter 1)
  • max-count)))

28
Tree Recursion
  • Fibonacci numbers 0, 1, 1, 2, 3, 5, 8, 13, 21,
    ...
  • 0
    if n 0
  • Fib( n ) 1
    if n 1
  • Fib(n-1) Fib(n-2)
    otherwise

(define (fib n) (cond (( n 0) 0)
(( n 1) 1) (else ( (fib (-
n 1)) (fib (- n
2))))))
29
Tree Recursion
Fib(5)
Fib(4)
Fib(3)
Fib(3)
Fib(2)
Fib(2)
Fib(1)
Fib(2)
Fib(1)
Fib(1)
Fib(0)
Fib(1)
Fib(0)
Fib(1)
Fib(0)
30
Tree Recursion
  • For Fibonacci numbers,
  • Use linear iteration instead of tree
    recursion
  • (define (fib n)
  • (fib-iter 1 0 n))
  • (define (fib-iter a b count)
  • (if ( count 0)
  • b
  • (fib-iter ( a b) a (- count 1))))

31
Exponentiation linear recursion
  • (define (expt b n)
  • (if ( n 0)
  • 1
  • ( b (expt b (- n 1)))))

32
Exponentiation linear iteration
  • (define (expt b n)
  • (exp-iter b n 1))
  • (define (exp-iter b counter product)
  • (if ( counter 0)
  • product
  • (exp-iter b
  • (- counter 1)
  • ( b product))))

33
Exponentiation fast method
bn (bn/2)2 if n is even bn b bn-1
if n is odd
  • (define (fast-exp b n)
  • (cond ( ( n 0) 1)
  • ( (even? n) (square (fast-exp b
    (/ n 2))))
  • (else ( b (fast-exp b (- n
    1))))))
  • (define (even? n)
  • ( (remainder n 2) 0))

34
Greatest Common Divisor
GCD( a , b ) is defined to be the largest integer
that evenly divides both a and b. GCD( a , b )
GCD( b , r ) where r is the remainder of a /
b. GCD(206, 40)GCD(40,6)GCD(6, 4)GCD(4,
2)GCD(2, 0)2
  • (define (gcd a b)
  • (if ( b 0)
  • a
  • (gcd b (remainder a b))))

35
Higher-Order Procedures
Build abstractions by assigning names to common
patterns (define (cube x) ( x x x)) Procedures
that manipulate data i.e. accept data as
argument and return data What about procedures
that manipulate procedures i.e. accept
procedures as argument and return
procedures Higher-Order Procedures
36
Procedures as Parameters
(define (sum-integers a b) (if (gt a b)
0 ( a (sum-integers ( a
1) b))))
  • (define (sum-cubes a b)
  • (if (gt a b)
  • 0
  • ( (cube a) (sum-cubes ( a 1) b))))

37
Procedures as Parameters
(define (ltnamegt a b) (if (gt a b)
0 ( (lttermgt a) (ltnamegt
(ltnextgt a) b))))
38
Procedures as Parameters
(define (sum term a next b) (if (gt a
b) 0 ( (term a)
(sum term (next a) next b))))
(define (sum-cubes a b) (define (inc x)
( x 1)) (sum cube a inc b))
39
Procedures using Lambda
Lambda define anonymous (lambda (x) ( x
1)) (lambda (ltformal-parametersgt) ltbodygt) (define
(sum-cubes a b) (sum (lambda (x) ( x x
x)) a (lambda (x)
( x 1)) b))
40
Procedures using Lambda
Lambda define anonymous (define (plus4 x) (
x 4)) (define plus4 (lambda (x) ( x 4))
41
Lambda Calculus
A lambda expression describes a "nameless"
function Specifies both the parameter(s) and the
mapping Consider this function cube (x) x x
x Corresponding lambda expr ?(x) x x x Can
be "applied" to parameter(s) by placing the
parameter(s) after the expression (?(x) x x
x)(3) The above application evaluates to 27
42
Lambda Calculus
Based on notation ? (lambda (l) (car (car
l))) l is called a "bound variable" think of
it as a formal parameter name Lambda expressions
can be applied ((lambda (l) (car (car l)))
'((a b) c d))
43
Lambda Examples
gt (define x 6) gt (lambda (x) ( x 1)) gt (define
inc (lambda (x) ( x 1))) gt (define same (lambda
(x) (x))) gt (if (even? x) inc same) gt ((if (even?
x) inc same) 5) 6
44
Lambda Examples
gt ((lambda(x) ( x 1)) 3) 4 gt (define fu-lst
(list (lambda (x) ( x 1)) (lambda (x) ( x
5)))) gt fu-lst (ltproceduregt ltproceduregt) gt
((second fu-lst) 6) 30
45
Internal Definitions
Internal definitions the special form, LET
(let ( (x (a b c)) (y (d e f))
) (cons x y)) Introduces a list of
local names (use define for top-level entities,
but use let for internal definitions) Each name
is given a value
46
Using Let to Define Local Variables
f(x,y) x(1 xy)2 y(1 y) (1 xy)(1
y) a 1 xy b 1 y f(x,y) xa2 yb ab
47
Using Let to Define Local Variables
(define (f x y) (define a ( 1 ( x
y))) (define b ( 1 y)) ( ( x
(square a)) ( y b) (
a b)))
48
Using Let to Define Local Variables
(define (f x y) (let ((a ( 1 ( x
y))) (b ( 1 y))) (
( x (square a)) ( y b)
( a b)))
49
Using Let to Define Local Variables
(define (f x y) ((lambda (a b)
( ( x (square a)) ( y
b) ( a b))) ( 1
( x y)) ( 1 y)))
50
Using Let to Define Local Variables
(let ((ltvar1gt ltexp1gt)
(ltvar2gt ltexp2gt)
(ltvarNgt ltexpNgt)) ltbodygt)
51
Procedures as Returned Values
The derivative of x3 is 3x2 Procedure
derivative Argument a function Return value
another function Derivative Procedure If f is a
function and dx is some number, then Df of f is
the function whose value at any number x is given
(limit of dx) by f(x dx)
f(x) D f(x) ----------------------
dx
52
Procedures as Returned Values
(define (deriv f dx) (lambda (x)
(/ (- (f ( x dx)) (f x))
(dx)))
gt ((deriv cube .001) 5) 75.015
53
Pairs
Compund Structure called Pair ltpairgt constructor
procedure cons ltheadgt ltrestgt ltheadgt extractor
procedure car ltpairgt ltrestgt extractor procedure
cdr ltpairgt (cadr ltarggt) (car (cdr
ltarggt)) (cons 1 2)
Box Pointer Representation
54
Pairs (continued)
(cons (cons 1 2) (cons 3 4))
(cons (cons 1 (cons 2 3)) 4)
55
Hierarchical Data
Pairs enable us to represent hierarchical
data hierarchical data data made up of
parts Data structures such as sequences and trees
56
Data Structures
Lists (list lta1gt lta2gt ... ltaNgt) is equal
to (cons lta1gt (cons lta2gt (cons ... (cons ltaNgt
nil))...) List Operations append, delete, list,
search, nth, len Sets gt (load e8.scm) Trees
gt (load e9.scm)
57
Symbols and Quote
(define a 1) (define b 2) (list a b) ? (1
2) (list a b) ? (a b) (car (a b c)) ?
a (cdr (a b c)) ? (b c)
58
Data Abstraction
from Primitive Data to Compund Data Real numbers
Rational numbers Operations on primitive data
, -, , / Operations on compound data rat,
-rat, rat, /rat Generic operators for all
numbers add, sub, mul, div
59
Rational Numbers
(define (make-rat n d) (cons n d)) (define
(numer x) (car x)) (define (denom x) (cdr
x)) (define (rat x y) (make-rat ( (
(numer x) (denom y))
( (denom x) (numer y))
( (denom x) (denom y))))
60
Use of Complex Numbers
Operations on compound data rat, -rat, rat,
/rat
c -c c /c
Complex arithmetic package
Rectangular representation
Polar representation
List structure and primitive machine arithmetic
61
Use of Numbers
Generic operators for all numbers add, sub,
mul, div
add sub mul div
Generic arithmetic package
rat rat rat /rat
c c c /c
/
Complex arithmetic
Real arithmetic
Rational arithmetic
Rectangular
Polar
List structure and primitive machine arithmetic
62
Complex Arithmetic - 1
z x i y where i2 -1 Real coordinate is
x Imaginary coordinate is y (define (make-rect x
y) (cons x y)) (define (real-part z) (car
z)) (define (imag-part z) (cdr z))
63
Complex Arithmetic - 2
z x i y r eiA Magnitude is r Angle is
A (define (make-polar r a) (cons ( r
(cos a)) ( r (sin a)))) (define (magnitude
z) (sqrt ( (square (car z)) (square
(cdr z))))) (define (angle z) (atan (cdr z)
(car z)))
64
Complex Arithmetic - 3
(define (c z1 z2) (make-rect (
(real-part z1) (real-part z2)) (
(imag-part z1) (imag-part z2)))) (define (c z1
z2) (make-polar ( (magnitude z1) (magnitude
z2)) ( (angle z1) (angle z2))))
65
Complex Arithmetic - 4
We may choose to implement complex numbers in
polar form instead of rectangular form. (define
(make-polar r a) (cons r a)) (define
(make-rect x y) (cons (sqrt ( (square
x) (square y))) (atan y x))) The discipline of
data abstraction ensures that the implementation
of complex-number operators is independent of
which representation we choose.
66
Manifest Types
A data object that has a type that can be
recognized and tested is said to have manifest
type. (define (attach-type type contents)
(cons type contents)) For complex numbers, we
have two types rectangular polar
67
Manifest Types
(define (type datum) (if (not (atom?
datum)) (car datum) (error
Bad typed datum Type datum))) (define
(contents datum) (if (not (atom?
datum)) (cdr datum) (error
Bad typed datum Contents datum)))
68
Complex Numbers
(define (make-rect x y) (attach-type
rect (cons x y))) (define (make-polar r
a) (attach-type polar (cons r
a))) (define (rect? z) (eq? (type z)
rect)) (define (polar? z) (eq? (type z)
polar))
69
Complex Numbers
(define (real-part z) (cond ( (rect? z)
(real-part-rect (contents z)))
( (polar? z)
(real-part-polar (contents z))))) (define
(imag-part z) (cond ( (rect? z)
(imag-part-rect (contents z)))
( (polar? z)
(imag-part-polar (contents z)))))
70
Complex Numbers
(define (real-part-rect z) (car z)) (define
(imag-part-rect z) (cdr z))
71
Complex Numbers
Use of complex numbers
c -c c /c
Complex arithmetic package
real-part imag-part magnitude
angle
Rectangular representation
Polar representation
List structure and primitive machine arithmetic
72
Data-Directed Programming
Previously, we implemented the mechanism that
interfaces the complex-arithmetic code with the
two representation packages as a set of
procedures that each perform an explicit dispatch
on type. Here we will implement the interface as
a single procedure that looks up the combination
of the operation name and argument type in the
table to find the correct procedure to apply, and
then applies it to the contents of the argument.
If we do this, then to add a new representation
package to the system we need not change any
existing procedures we need only add new entries
to the table.
73
Data-Directed Programming
Data-directed programming is the technique of
designing programs to work with such a table
directly.
74
Data-Directed Programming
To implement this plan, assume that we have two
procedures, put and get, for manipulating the
operation-and-type table (put ltopgt lttypegt
ltitemgt) installs the ltitemgt in the table, indexed
by the ltopgt and the lttypegt. (get ltopgt
lttypegt) looks up the ltopgt, lttypegt entry in the
table and returns the item found there. If no
item is found, get returns false.
75
Data-Directed Programming
(put 'real-part 'rectangular real-part-rect) (put
'imag-part 'rectangular imag-part-rect) (put
'magnitude 'rectangular magnitude-rect) (put
'angle 'rectangular angle-rect) (put 'real-part
'polar real-part-polar) (put 'imag-part 'polar
imag-part-polar) (put 'magnitude 'polar
magnitude-polar) (put 'angle 'polar angle-polar)
76
Data-Directed Programming
(define (operate op obj) (let ((proc (get op
(type obj)))) (if (not (null? proc)) (proc
(contents obj)) (error Operator
undefined (list op obj)))))
77
Data-Directed Programming
(define (real-part obj) (operate 'real-part
obj)) (define (imag-part obj) (operate 'imag-part
obj)) (define (magnitude obj) (operate 'magnitude
obj)) (define (angle obj) (operate 'angle obj))
78
SUPPLEMENT
79
Let Expressions
(let ((a 4) (b -3)) (let ((a-squared ( a a))
(b-squared ( b b))) ( a-squared
b-squared))) 25
80
Let Expressions
(let ((x 1)) (let ((x ( x 1))) ( x x))) 4
81
Let Expressions
Shadowing may be avoided by choosing different
names for variables. The expression above could
be rewritten so that the variable bound by the
inner let is new-x. (let ((x 1)) (let ((new-x
( x 1))) ( new-x new-x))) 4
82
Lambda Expressions
((lambda (x) ( x x)) ( 3 4)) ? 24 Because
procedures are objects, we can establish a
procedure as the value of a variable and use the
procedure more than once. (let ((double (lambda
(x) ( x x)))) (list (double ( 3 4))
(double (/ 99 11)) (double (- 2 7)))) ?
(24 18 -10)
83
Lambda Expressions
(let ((double-any (lambda (f x) (f x x))))
(list (double-any 13) (double-any cons
'a))) ? (26 (a . a))
84
Lambda Expressions
(define double-any (lambda (f x) (f x
x))) The variable double-any now has the same
status as cons or the name of any other primitive
procedure. We can use double-any as if it were a
primitive procedure. (double-any 10) ?
20 (double-any cons 'a) ? (a . a)
85
Lambda Expressions
(map abs '(1 -2 3 -4 5 -6)) ? (1 2 3 4 5 6) (map
cons '(a b c) '(1 2 3)) ? ((a . 1) (b . 2) (c .
3)) (map (lambda (x) ( x x)) '(1 -3 -5 7)) ? (1
9 25 49)
86
Lambda Expressions
(define map1 (lambda (p ls) (if (null? ls)
'() (cons (p (car ls))
(map1 p (cdr ls)))))) (map1 abs '(1 -2 3 -4 5
-6)) ? (1 2 3 4 5 6)
87
Lambda Expressions
(let ((x 'a)) (let ((f (lambda (y) (list x
y)))) (f 'b))) ? (a b) The occurrence of x
within the lambda expression refers to the x
outside the lambda that is bound by the outer let
expression. The variable x is said to occur free
in the lambda expression or to be a free variable
of the lambda expression. The variable y does
not occur free in the lambda expression since it
is bound by the lambda expression.
88
Free Bound Variables
gt (occurs-free? x x) t gt (occurs-free? x
y) f gt (occurs-free? x (lambda (x) (x
y))) f gt (occurs-free? x (lambda (y) (x
y))) t gt (occurs-free? x ((lambda (x) x) (x
y))) t gt (occurs-free? x (lambda (y) (lambda
(z) (x (y z))))) t
89
Free Bound Variables
We can summarize these cases in the rules If
the expression e is a variable, then the variable
x occurs free in e if and only if x is the same
as e. If the expression e is of the form
(lambda (y) e), then the variable x occurs free
in e if and only if y is different from x and x
occurs free in e. If the expression e is of the
form (e1 e2), then x occurs free in e if and only
if it occurs free in e1 or e2. Here, we use or
to mean inclusive or, meaning that this includes
the possibility that x occurs free in both e1 and
e2. We will generally use or in this sense.
90
Free Bound Variables
(define occurs-free? (lambda (var
exp) (cond ((symbol? exp) (eqv? var
exp)) ((eqv? (car exp) lambda) (and
(not (eqv? var (car (cadr exp)))) (occurs-free
? var (caddr exp)))) (else (or (occu
rs-free? var (car exp)) (occurs-free? var
(cadr exp)))))))
Write a Comment
User Comments (0)
About PowerShow.com