Presentation is loading. Please wait.

Presentation is loading. Please wait.

The “Beauty” of Scheme: Programs as Proofs Q: Is '(abc 123) a list? A: Yes Proof:  '(abc 123) = (cons 'abc (cons 123 '()))  '() is a list, so (cons 123.

Similar presentations


Presentation on theme: "The “Beauty” of Scheme: Programs as Proofs Q: Is '(abc 123) a list? A: Yes Proof:  '(abc 123) = (cons 'abc (cons 123 '()))  '() is a list, so (cons 123."— Presentation transcript:

1 The “Beauty” of Scheme: Programs as Proofs Q: Is '(abc 123) a list? A: Yes Proof:  '(abc 123) = (cons 'abc (cons 123 '()))  '() is a list, so (cons 123 '()) is also a list  (cons 123 '()) is a list, so (cons 'abc (cons 123 '())) is also a list, Q.E.D.

2 The Beauty of Scheme: Programs as Definitions Base-case: fac(0) = 1 Induction: fac(n) = n * fac(n-1) Factorial: program (define fac (lambda(n) (if (eq? n 0) 1 (* n (fac (- n 1))))) Factorial: definition

3 The Power of Scheme: Functions as First-Class Objects ; apply a function to each number in a list (define map (lambda (fn ln) ; function, list of numbers (if (null? ln) ; null? means equals '() '() (cons (fn (car ln)) ; apply fn to first elmt (map fn (cdr ln)))))) ; recur on rest > (map square '(1 2 3 4 5)) (1 4 9 16 25)

4 Shortcuts: cond (define (sign x) (if (< x 0) (if (> x 0) 1 0))) (define (sign x) (cond ((< x 0) -1) ((> x 0) 1) (else 0))) ; sensible default

5 Shortcuts: list-ref If ls is a list then (car ls) = (list-ref ls 0) (car (cdr ls)) = (list-ref ls 1) (car (cdr (cdr ls)) = (list-ref ls 2) (Like Java/C++ arrays)

6 Shortcuts: car, cdr (caar ls) = (car (car ls)) (cadr ls) = (car (cdr ls)) (cdadr ls) = (cdr (car (cdr ls))) (etc.)

7 Comparison with Python/Java/C++ Binding instead of assignment: (define a 5) vs. a = 5;

8 Comparison with Python/Java/C++ Recursion instead of loops: int sum(int n) { // sum from 0 to n int s = 0; for (int i=1; i<=n; ++i) { s += i; } return s; } (define sum (lambda (n) (if (eq? n 0) 0 (+ n (sum (- n 1)))))

9 Interpreter: The Read/Eval/Print Loop > 1 1 > (+ 3 2) 5 > ((lambda(x) (* x x)) 4) 16

10 Getting Started We'll use DrScheme (a.k.a. PLT Scheme, a.k.a. DrRacket):  Runs under Unix, Mac, Windows  Integrated with EOPL  Nice help environment At Unix prompt, type drscheme, or download from www.drscheme.org Help / About DrScheme / Take A Tour Try some examples from lecture: > (load " filename. scm")


Download ppt "The “Beauty” of Scheme: Programs as Proofs Q: Is '(abc 123) a list? A: Yes Proof:  '(abc 123) = (cons 'abc (cons 123 '()))  '() is a list, so (cons 123."

Similar presentations


Ads by Google