# An Introduction to Scheme

Size: px
Start display at page:

Transcription

1 An Introduction to Scheme Stéphane Ducasse Stéphane Ducasse 1

2 Scheme Minimal Statically scoped Functional Imperative Stack manipulation Specification in a couple of pages 2

3 RoadMap Execution principle Basic elements Pairs and Lists Function definition Some special forms One example of function 3

4 Conventions...? for predicates equal?, boolean?...! for side-effect set! *global* char-, string-, vector- procedures

5 Read-Eval-Print Read an expression Evaluate it Print the result and goto 1. read eval print Using a Scheme interpreter > (+ 1 3) 4 In this document 5

6 Implication An interpreter always gets the value of an expression Different kinds of expression, forms, gets evaluated differently some are self-evaluating: boolean, characters, numbers user-defined functions evaluate all their arguments special forms evaluate some of their arguments (if, when, set!, define, lambda,...) Prefix (+ 1 2) Value of first element applied on values of the rest

7 Examples > 4 ;; self-evaluable 4 > -5-5 > (* 5 6) ;; applying * 30 > ( ) ;; applying + 20 > (* 4 (* 5 6)) ;; nested expressiosn 120 > (* 7 (- 5 4) 8) 56 > (- 6 (/ 12 4) (* 2 (+ 5 6)))

8 Function Examples (define (square nb) ;; return the square of a number ;; nb -> nb (* nb nb)) (square 9) => 81 (square 4) => 16 8

9 RoadMap Execution principle Basic elements Pairs and Lists Function definition Some special forms One example of function 9

10 Basic Elements Simple data types booleans numbers characters strings

11 Booleans #t and #f (not #f ) => #t (and (= 2 2) (> 2 1)) => #t (or (= 2 2) (> 2 1)) => #t (or (= 2 2) (< 2 1)) => #t 11

12 Booleans #t and #f (boolean? #t) => #t (boolean? hello ) => #f self-evaluating > #t #t

13 Numbers self-evaluating 1.2 => 1.2 1/2 => 1/2 1 => 1 2+3i => 2+3i

14 Number Comparison Numbers can tested for equality using the generalpurpose equality predicate eqv? (eqv? ) => #t (eqv? 42 #f ) => #f (eqv? ) => #f However, if you know that the arguments to be compared are numbers, the special number-equality predicate =is more apt. (= ) => #t (= ) => #t Other number comparisons allowed are <,<=,>,>=.

15 Numbers Operations ( ) => 6 ( ) => 3.3 ( ) => 2 (* 1 2 3) => 6 (/ 6 3) => 2 (/22 7) => 22/7 (expt 23) => 8 (expt 4 1/2) => 2.0 (-4) => -4 (/4) => 1/4 (max ) => 4 (min )=> 1 (abs 3) => 3

16 Number Predicates (number? 42) => #t (number? #t) => #f (complex? 2+3i) => #t (real? 2+3i) => #f (real? ) => #t (real? 22/7) => #t (real? 42) => #t (rational? 2+3i) => #f (rational? ) => #t (rational? 22/7) => #t (integer? 22/7) => #f (integer? 42) => #t

17 Strings abc d d self-evaluating abc => abc (string #\s #\q #\u #\e #\a #\k) => squeak (string-ref squeak 3) => #\e (string-append sq ue ak ) => squeak (define hello hello ) (string-set! hello 1 #\a) hello => hallo (string? hello) => #t

18 Symbols identifiers for variable x, this-is-a-symbol,i18n,<=> Not self-evaluating Evaluation returns their value Symbols are unique compared to strings > (eq? (string->symbol "blabla") (string->symbol "blabla")) #t > (eq? "blabla" "blabla") #f 18

19 Assigning Value (define symbol expr) define a new symbol having as value the value of expr (set! symbol expr) change the value of symbol to be the one of expr > (define xyz (+ 5 5) > xyz 10 > (set! xyz (* 2 xyz)) > xyz 20

20 Quote How to manipulate a variable and not its value? Quote it! a => a (* 2 3) => (* 2 3) ;; a list Remember: Something => Something Elephant => Elephant Elephant => Elephant 20

21 RoadMap Execution principle Basic elements Pairs and Lists Function definition Some special forms One example of function

22 Pairs Two values: an ordered couple, a pair (cons a b) => (a. b) (car (cons a b)) => a (cdr (cons a b)) => b Not self-evaluating (1. #t) => (1. #t) (1. #t) => Error

23 A Graphical Notation (cons 'a 'b) => (a. b) a (cons 'a (cons 'b 'c) => (a. (b. c)) b a b c

24 Nested Pairs (cons (cons 1 2) 3) => ((1. 2). 3) (car (cons (cons 1 2) 3)) => (1. 2) (cdr (car (cons (cons 1 2) 3))) => 2 (car (car (cons (cons 1 2) 3))) => 1 (caar (cons (cons 1 2) 3)) => 1 Notation (cons 1 (cons 2 (cons 3 (cons 4 5)))) => ( ) <=> (1. ( 2. ( 3. ( 4. 5))))

25 The Empty List Empty list: () () => () (null? (a b)) => #f (null? ()) => #t (pair? ()) => #f

26 List and Pairs (a. ())) = (a) A list is either the empty list or a pair whose cdr is a list a (cons 'a (cons 'b '()) => (a b) a (cons 1 ()) => (1. ()) <=> (1) b ( ) <=> (1. (2. (3. (4. ())))) <=> (cons 1 (cons 2 (cons 3 (cons 4 ())))

27 Consequences... (car (a b c d)) => a (cdr (a b c d)) => (b c d) (cons a (b c d)) => (a b c d) (car ()) => Error (cdr ()) => Error (pair? ()) => #f (null? ()) => #t

28 List Predicates (pair? '(1.2)) => #t (pair? '(1 2)) => #t (pair? '()) => #f (list? '()) => #t (null? '()) => #t (list? '(1 2)) => #t (list? '(1.2)) => #f (null? '(1 2)) => #f (null? '(1.2)) => #f

29 (List...) (list...) evaluates all its arguments and create a list with results > (list 1 (+ 1 2) 3 4) => ( ) > (list a b c) => (a b c) > ( ) => ( )

30 (Append...) (append l1 l2..) Evaluates its arguments and returns the concatenation of the results (append (a b c) (d e) (a)) > (a b c d e a) (append (a b c) ()) > (a b c)

31 List Evaluation List evaluation is function application Examine the first element of the s-expression. If the head evaluates to a procedure, the rest of the form is evaluated to get the procedure's argument values, and the procedure is applied to them. User-defined functions evaluate this way. Applicative order

32 List evaluation (+ (* 3 2) 4) + => procedure (* 3 2) => same process => 6 4 => 4 => 10 32

33 Quote and List Quote forces lists to be treated as data (define x (cons a b)) x => (cons a b) (list? x) => #t (pair? x) => #t (quote '()) => '() ''() => '()

34 Food for thought (cons car cdr) (list this (is silly)) (cons is (this silly?)) (quote (+ 2 3)) (cons + (2 3)) (quote cons) (quote (quote cons)) ((car (list + - *)) 2 3)

35 RoadMap Execution principle Basic elements Function definition Some special forms One example of function 35

36 Procedure cons => #<primitive:cons> cons is a global variable referring to the primitive cons procedure (car (+ 1 2)) => + (car (list + 1 2)) => #<primitive:+>

37 User Defined Procedure (define (name arguments) body) (define (id x) x) f => #<procedure:f> > (id 3) 3 > (id a) a

38 Main Definition Form (define (name x y) body) (define (square x) (* x x))

39 Recursive definitions... (define (length l) (if (null? l) 0 (+ 1 (length (cdr l))) (define (useless l) (if (null? l) () (cons (car l) (useless (cdr l))) 39

40 Towards map (define (mymap f l) (if (null? l) '() (cons (f (car l)) (mymap f (cdr l))))) 40

41 (map... (map abs '(1-2 3)) > (1 2 3) (map abs '(1 (-2) 3)) > error (map cons '(1 2 3) '(a b c)) > ((1. a) (2. b) (3. c)) (map (lambda (x) (* x x)) '(1 2 3)) > (1 4 9) 41

42 define and lambda (define (square x) (* x x)) (define square (lambda (x) (* x x))) 42

43 Compose (define compose (lambda (g f) (lambda (x) (g (f x))))) ((compose (lambda (x) (+ x 2)) (lambda (x) (* 3 x))) 7) => 23 43

44 RoadMap Variables Environment Let, Let*, Letrec The notion of closure High-order functions 44

45 define, lambda and let (define (f x) (define (f-help y) (/ (+ y 1) (- y 1))) (f-help (square x))) (define (f x) ((lambda (y) (/ (+ y 1) (- y 1))) (square x))) Binds y to (square x) (define (f x) (let ((y (square x))) (/ (+ y 1) (- y 1)))) 45

46 Lambda... ((lambda (formal parameters) body) arguments) creates bindings from formal parameter with arguments and evaluates body (define x 20) ;; modifies the lexical binding of a variable (define add2 (lambda (x) (set! x (+ x 2)) x)) (add2 3) => 5 (add2 x) => 22 x => 20 46

47 Let & Lambda (let ((variable-1 expression-1) (variable-2 expression-2)... (variable-n expression-n)) body) is syntactic sugar for ((lambda (variable-1...variable-n) body) expression-1... expression-n) 47

48 Let and Lambda (let ((x (* 4 5)) (y 3)) (+ x y)) is equivalent to ((lambda (x y) (+ x y)) (* 4 5) 3) 48

49 (Let... (let [(x 2) (y 3)] (* x y)) => 6 Bindings are evaluation order is not relevant. (let [(x 2) (y 3)] (let [(x 7) (z (+ x y))] (* z x))) => 35 [ is the same as ( it is just more readable When binding z only (x 2) is visible. 49

50 Let Examples (let [(x 1) (y 2) (z 3)] (list x y z)) => (1 2 3) (define x 20) (let [(x 1) (y x)] (+ x y)) => 21 (let [(cons (lambda (x y) (+ x y)))] (cons 1 2)) => 3 50

51 (Let* (let [(x 2) (y 3)] (let* [(x 7) (z (+ x y))] (* z x))) => 70 (let* [(x 1) (y x)] (+ x y)) => 2 equivalent to (let [(x 1)] (let [(y x)] (+ x y))) => 2 51

52 Where let is not enough (let ((sum (lambda (ls) (if (null? ls) 0 (+ ( car ls) (sum (cdr ls))))))) (sum '( ))) > reference to undefined identifier sum 52

53 Passing itself (let ((sum (lambda (s ls) (if (null? ls) 0 (+ ( car ls) (s s (cdr ls))))))) (sum sum '( ))) Works but not really satisfactory 53

54 Let is not enough (let [(local-even? (lambda (n) (if (= n 0) #t (local-odd? (- n1))))) (local-odd? (lambda (n) (if (= n 0) #f (local-even? (- n 1)))))] (list (local-even? 23) (local-odd? 23))) local-even? and local-odd? don't refer to the variables we are defining but other in parent environment. Changing the let to a let* won't work either, local-even? inside localodd? 's body refers to the correct procedure value, the local-odd? in local-even? 's body still points elsewhere. 54

55 (letrec... (letrec ((var expr)...) body) extends the current environment with vars with undefined values and associate to the vars the value of exprs evaluated within this environment. (letrec [(local-even? (lambda (n) (if (= n 0) #t (local-odd? (- n 1))))) (local-odd? (lambda (n) (if (= n 0) #f (local-even? (- n 1)))))] (list (local-even? 23) (local-odd? 23))) 55

56 Variables and Env (i) > n ERROR: Undefined global variable n > (define n 5) > n 5 > (* 4 n) 20 (define name expression) (set! name expression) (lambda... (let... 56

57 Variable and Env (ii) In Scheme one single value for a symbol used as operator or operand > (\$ 4 5) ERROR: Undefined global variable \$ > (define \$ +) > (\$ 4 5) 9 > (define som +) > (som 4 5) 9 57

58 Lexical Scope (define (test a b) (+ a b c)) > (test 1 2) reference to undefined identifier: c > (define (top-test c) (test 1 2)) > (top-test 3) reference to undefined identifier: c See more with closure 58

59 Closure Closure: Environment + function (let [(a 5)] (let [(f (lambda (x) (+ x a))) (a 0)] (f 10))) => 15 Lambda refers to it environment! (let [(a 5)] (let [(f (lambda (x) (+ x a)))] (set! a 0) (f 10))) => 10 59

60 Creation Time Binding The same bindings that were in effect when the procedure was created are in effect when it is applied (let ((m (let ((x 2)) (lambda (y) (list x y))))) (let ((x 3)) (m 4))) > (2 4) 60

61 Spying Cons... (define cons-count 0) (define cons (let ([old-cons cons]) (lambda (x y) (set! cons-count (+ cons-count 1)) (old-cons x y)))) >(cons 'a 'b) (a. b) > cons-count 1 >(list 1 2 3) > cons-count 1 61

62 A Simple Counter (define counter 0) (define bump-counter (lambda () (set! counter (+counter 1)) counter)) (bump-counter) => 1 (bump-counter) => 2 Simple because everybody can change it and we can only have one 62

63 Counters... (define next 0) (define count (lambda () (let ([v next]) (set! next (+ next 1)) v))) next visible by others! (define count (let ([next 0]) (lambda () (let ([v next]) (set! next (+ next 1)) v)))) Now next is private to count 63

64 Counters... (define make-counter (lambda () (let ([next 0]) (lambda () (let ([v next]) (set! next (+ next 1)) v))))) > (define c1 (make-counter) > (c1) (c1) 1 > (define c2 (make-counter)) > (c2) 1 64

65 Kind of objects (define (make-fib-counter) (let ((nb 0)) (letrec ((fib (lambda (n) (set! nb (+ 1 nb)) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))))) (lambda message (case (car message) ((fib) (fib (cadr message))) ((nb) nb) ((reset) (set! nb 0))))))) >(define fibc (make-fib-counter)) >(fibc 'fib 6) 8 > (fibc 'nb) 25 ;; number of recursive calls 65

66 RoadMap Execution principle Basic elements Function definition Some special forms One example of function 66

67 Special Forms Some forms have specific evaluation strategy Example (if test truecase falsecase) does not evaluate all its arguments! Hopefully! (lambda does not evaluate its argument) Some special forms are: define, set!, cond, if, lambda... We will see how to define special forms in the future

68 Sequence (begin exp1... expn) evaluates exp1...expn and returns the value of expn (begin (display "really!") (newline) (display "squeak is cool!")) Scheme is not a pure functional language, it favors functional style but enables also imperative programming

69 (If...) (if (char<? c#\c ) -1 (if (char=? c#\c ) 0 1))

70 (Cond...) (cond ((predicate-expr1) actions1...) ((predicate-expr2) actions2...)... (else actionsn...)) when predicate-expri is true, executes actionsi and returns the value of the last actionsi

71 Cond Example (cond ((char<? c#\c ) -1) ((char=? c#\c ) 0) (else 1)) The cond actions are implicit begin s

72 (case...) (case #\e ((#\a) 1) ((#\b) 2) ((#\c #\e) 3) (else 4)) > 3 (case (car (a b)) ( a 1) ( b 2))

73 Let (let ((variable-1 expression-1) (variable-2 expression-2)... (variable-n expression-n)) body) (let ((x (* 4 5)) (y 3)) (+ x y))

74 Macros Mechanism needed when the language needs to be extended with new constructions Provide an easy way to control evaluation of arguments. New special forms can be defined as macros 74

75 Adding ifnot: ifn Problem: How to add ifn such as: (ifn expr then else) => then if expr is false, else else A first (not working) solution: (define (ifn expr then else) (if (not expr) then else)) What does the following do? (ifn (= 1 2) (display foo ) (display bar )) 75

76 Defining a special form Arguments passed to ifn should not be evaluated. So ifn cannot be described with a simple function. A macro has to be used: (define-macro (ifn test then else) (list if test else then) Two phases: 1) macro-expansion: syntactic rewriting 2) evaluation in the current environment of the resulting expression 76

77 ifn decomposed The expression: (ifn (= 1 2) (display foo ) (display bar )) is first rewritten as: (if (= 1 2) (display bar ) (display foo )) and then evaluated: >foo 77

78 In the need for macrocharacters Here an example that can be simplified: (define-macro (when test s1. Lbody) (list 'if test (append (list 'begin s1) Lbody) #f)) Same with macrocharacters (define-macro (when test s1. Largs) `(if,test #f)) 78

79 Macrocharacters Useful for lighter macro definitions ` is almost equivalent to except arguments preceded by, are evaluated. (define-macro (ifn test then else) retrieve the contents of the list (let ((a abc) (b (1 2 3)) => (abc (1 2 3) 1 2 3) 79

80 New Iterators > (map list '(1 (2) 3)) ((1) ((2)) (3)) (define (append-map f L) (apply append (map f L)) >(append-map list '(1 (2) 3)) (1 (2) 3) (define (flatten s) (if (list? s) (append-map flatten s) (list s))) >(flatten '(((1)) (1) 1)) (1 1 1) 80

81 New Iterators (define (map-select f L p?) (append-map (lambda (x) (if (p? x) (list (f x)) ())) L)) > (map-select (lambda (x) (+ 10 x)) '( ) (lambda (x) (odd? x))) (11 13) (define (every f L) (if (null? L) #t (and (f (car L)) (every f (cdr L)))) 81

82 Sums... (define (sum-ints a b) (if (> a b) 0 (+ a (sum-ints (+ a 1) b)))) (sum-ints 3 7) => 25 (define (sum-sqrs a b) (if (> a b) 0 (+ (square a) (sum-sqrs (+ 1 a) b)))) (sum-sqrs 3 7) => 135 (define (sum term next a b) (if (> a b) 0 (+ (term a) (sum term next (next a) b)))) (sum id plus-one 3 7) 82

83 Compose (define compose (lambda (g f) (lambda (x) (g (f x))))) ((compose (lambda (x) (+ x 2)) (lambda (x) (* 3 x))) 7) => 23 83

84 Compose at Work (define fth (compose car cddddr)) > (fth '( )) 5 84

85 Derivation Dg(x) = (g(x+dx) - g(x)) / dx (define dx ) (define (deriv g) (lambda (x) (/ (- (g (+ x dx)) (g x)) dx))) (define (cube x) (* x x x)) 85

86 Capture (define capture (lambda l (lambda (f) (f l)))) Currification (define onetosix (capture )) >(onetosix car) 1 >(onetosix (lambda (x) 86

87 Continuations How to escape the current computation after an error? How to discard pending computation? How to control the future computation? Applications Advanced control flow Escaping mechanism Web server Difficulty escaping a computation > (+ ( 1000 (abort (* 2 3))) ( )) > 6 87

88 Continuations 88

89 Two Approaches Explicit continuation of a computation Continuation Passing Style CSP by adding a new parameter that represents the current continuation of the computation Using call/cc which captures the current continuation 89

90 CSP: Manual Continuation (define (foo x) is transformed into (define (k-foo x cont) so that k-foo returns (cont (foo x)) Pros control the future of the computation can give up and choose another future can be stored of passed to another functions Cons tedious 90

91 Factorial-k (define (fac n) (if (= 0 n) 1 (* n (fac (- n 1))))) (define (kfac n k)...?? (kfac 5 (lambda (x) x)) 120 (kfac 5 (lambda (x) (+ 2 x)))

92 Getting Factorial-k (kfac 0 k) = (k (fac 0)) = (k 1) (kfac n k) = (k (fac n)) = (k (* n (fac (- n 1))) = (kfac (- n 1) (lambda (v) (k (* n v)))) (define (kfac n k) ;; n * k = function of one arg (if (= 0 n) (k 1) (kfac (- n 1) (lambda (v) (k (* n v)))))) 92

93 How computation works.. (+ 3 (* 4 (+ 5 6))) first results in 11 then * 4 then + 3 Once (+ 5 6) is evaluated the rest of the computation to continue is * 4 and

94 Contexts A context is a procedure of one variable [] (hole) How to create a context? Two steps: - replace expression by [] - form a lambda (+ 3 (* 4 (+ 5 6))) context of (+ 5 6) = (lambda ([]) (+ 3 ( * 4 []))) 94

95 Contexts (ii) Refined two Steps - replace expression by [] and evaluate it as much as we can - then we form a lambda (if (zero? 5) (+ 3 (* 4 (+ 5 6))) (* (+ (* 3 4) 5) 2)))) Context of (* 3 4) is (lambda ([]) (* (+ [] 5) 2)) 95

96 Context of (* 3 4) (let ((n 1)) (if (zero? n) (writeln (+ 3 (* 4 (+ 5 6)))) (writeln (* (+ (* 3 4) 5) 2))) n) is (lambda ([]) (begin (writeln (* (+ [] 5) 2) n) with the closure environment having n bound to 1 96

97 Execute... (define (mapadd l) (if (null? l) (cons (+ 3 (* 4 5)) '()) (cons (+ 1 (car l)) (mapadd (cdr l))))) (mapadd '(1 3 5)) > ( ) Context of (* 4 5) in (cons 0 (mapadd (1 3 5)))? (lambda ([]) (cons 0 (cons 2 (cons 4 (cons 6 (cons (+ 3 []) ())))))) 97

98 Roadmap Context Escaper Continuation 98

99 Escape Procedures Yields a value but never passes that value to others. The value of an escape procedures is the value of the entire computation Anything awaiting its result is ignored (+ (escape-* 5 2) 3) > 10 (* 100 (+ 30 (escape-* 5 2))) > 10 99

100 Escaper (+ ((escaper (lambda (x) ((escaper -) ((escaper *) x 3) 7))) 5) 4) >

101 Roadmap Context Escaper Continuation 101

102 Continuation (...(call/cc (lambda (k)...k...)...) We pass the rest of the computation, i.e., the context of (call/cc..) as an escaper to k 102

103 Continuation Evaluation (1) form the context of (call/cc cont) (lambda []...) (2) create an escaper (escaper (lambda []...) (3) pass (escaper (lambda []...) to cont where cont = (lambda (k)...) If cont uses the escaper k then it escapes! Else the normal value mechanism is applied 103

104 Example (+ 3 (* 4 (call/cc (lambda (k)...))) Context of (call/cc...) (lambda ([]) (+ 3 (* 4 []))) We have then (+3 (* 4 ((lambda (k)...) (escaper (lambda ([]) (+ 3 (* 4 []))))) The context of call/cc is escaped and passed as k 104

105 Call/cc (call-with-current-continuation proc) Proc must be a procedure of one argument. The procedure call-with-currentcontinuation packages up the current continuation as an escape procedure and passes it as an argument to proc. The escape procedure is a Scheme procedure that, if it is later called, will abandon whatever continuation is in effect at that later time and will instead use the continuation that was in effect when the escape procedure was created. [...] The escape procedure that is passed to proc has unlimited extent just like any other procedure in Scheme. It may be stored in variables or data structures and may be called as many times as desired. 105

106 Example (call/cc (lambda (k) (+ 2 (* 7 (k 3)))) > 3 k = (escaper (lambda ([]) [])) (+ 1 (call/cc (lambda (k) (+ 2 3)))) > 6 k = (escaper (lambda ([]) (+ 1 []))) but k not invoked (+ 1 (call/cc (lambda (k) (+ 2 (k 3))))) > 4 k = (escaper (lambda ([]) (+ 1 []))) = (lambda^ ([]) (+ 1 []))) k invoked 106

107 Escaping on Error (define (product l) (call/cc (lambda (exit) (letrec ((proaux (lambda (l) (cond ((null? l) 1) ((not (number? (car l))) (exit 'error)) ((zero? (car l)) (exit 0)) (else (* (car l) (proaux (cdr l)))))))) (proaux l))))) (product '(42 27 q )) > error (+ 3 (product '(42 27 q ))) >+: expects type <number> as 2nd argument, given: erreur; other arguments were: 3 107

### Functional Programming. Pure Functional Programming

Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

### LECTURE 16. Functional Programming

LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

### Notes on Higher Order Programming in Scheme. by Alexander Stepanov

by Alexander Stepanov August 1986 INTRODUCTION Why Scheme? Because it allows us to deal with: 1. Data Abstraction - it allows us to implement ADT (abstact data types) in a very special way. The issue of

### Organization of Programming Languages CS3200/5200N. Lecture 11

Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages

### COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

### Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

Scheme Tutorial Introduction Scheme is an imperative language with a functional core. The functional core is based on the lambda calculus. In this chapter only the functional core and some simple I/O is

### Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions

### Introduction to Scheme

How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free

### Functional Programming. Pure Functional Languages

Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

### Chapter 1. Fundamentals of Higher Order Programming

Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

### Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

### A Brief Introduction to Scheme (II)

A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data

### Functional Programming. Pure Functional Languages

Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

### Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Scheme in Scheme: The Metacircular Evaluator Eval and Apply CS21b: Structure and Interpretation of Computer Programs Brandeis University Spring Term, 2015 The metacircular evaluator is A rendition of Scheme,

### Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs Lexical addressing The difference between a interpreter and a compiler is really two points on a spectrum of possible

### An introduction to Scheme

An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize

### Deferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action.

Deferred operations Continuations 6.037 - Structure and Interpretation of Computer Programs Mike Phillips (define the-cons (cons 1 #f)) (set-cdr! the-cons the-cons) (define (run-in-circles l) (+

### Scheme Quick Reference

Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

### 6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator

### 11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

Functional programming FP Foundations, Scheme (2 In Text: Chapter 15 LISP: John McCarthy 1958 MIT List Processing => Symbolic Manipulation First functional programming language Every version after the

### SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

### Functional Languages. Hwansoo Han

Functional Languages Hwansoo Han Historical Origins Imperative and functional models Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s Different formalizations of the notion of an algorithm

### Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003 CS 314, LS, LTM: Functional Programming 1 Scheme A program is an expression to be evaluated (in

### Scheme Quick Reference

Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

### FP Foundations, Scheme

FP Foundations, Scheme In Text: Chapter 15 1 Functional Programming -- Prelude We have been discussing imperative languages C/C++, Java, Fortran, Pascal etc. are imperative languages Imperative languages

### SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

### 6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter

6.037 Lecture 4 Interpretation Interpretation Parts of an interpreter Meta-circular Evaluator (Scheme-in-scheme!) A slight variation: dynamic scoping Original material by Eric Grimson Tweaked by Zev Benjamin,

### Programming Languages

Programming Languages Tevfik Koşar Lecture - XIII March 2 nd, 2006 1 Roadmap Functional Languages Lambda Calculus Intro to Scheme Basics Functions Bindings Equality Testing Searching 2 1 Functional Languages

### COP4020 Programming Assignment 1 - Spring 2011

COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to

### CSC 533: Programming Languages. Spring 2015

CSC 533: Programming Languages Spring 2015 Functional programming LISP & Scheme S-expressions: atoms, lists functional expressions, evaluation, define primitive functions: arithmetic, predicate, symbolic,

### Turtles All The Way Down

Turtles All The Way Down Bertrand Russell had just finished giving a public lecture on the nature of the universe. An old woman said Prof. Russell, it is well known that the earth rests on the back of

### Documentation for LISP in BASIC

Documentation for LISP in BASIC The software and the documentation are both Copyright 2008 Arthur Nunes-Harwitt LISP in BASIC is a LISP interpreter for a Scheme-like dialect of LISP, which happens to have

### Functional Programming

Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 16: Functional Programming Zheng (Eddy Zhang Rutgers University April 2, 2018 Review: Computation Paradigms Functional: Composition of operations on data.

### Functional Programming. Big Picture. Design of Programming Languages

Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

### Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)

### regsim.scm ~/umb/cs450/ch5.base/ 1 11/11/13

1 File: regsim.scm Register machine simulator from section 5.2 of STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS This file can be loaded into Scheme as a whole. Then you can define and simulate machines

Administrivia Lists, higher order procedures, and symbols 6.037 - Structure and Interpretation of Computer Programs Mike Phillips (mpp) Massachusetts Institute of Technology Project 0 was due today Reminder:

### Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

.00 SICP Interpretation part Parts of an interpreter Arithmetic calculator Names Conditionals and if Store procedures in the environment Environment as explicit parameter Defining new procedures Why do

### 1.3. Conditional expressions To express case distinctions like

Introduction Much of the theory developed in the underlying course Logic II can be implemented in a proof assistant. In the present setting this is interesting, since we can then machine extract from a

### Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

Streams, Delayed Evaluation and a Normal Order Interpreter CS 550 Programming Languages Jeremy Johnson 1 Theme This lecture discusses the stream model of computation and an efficient method of implementation

### CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal) What is the Metacircular Evaluator? It is the best part

### Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Scheme: Data CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu

### Scheme: Strings Scheme: I/O

Scheme: Strings Scheme: I/O CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Wednesday, April 5, 2017 Glenn G. Chappell Department of Computer Science University of

### CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

CS 61A Spring 2019 Guerrilla Section 5: April 20, 2019 1 Interpreters 1.1 Determine the number of calls to scheme eval and the number of calls to scheme apply for the following expressions. > (+ 1 2) 3

### CSc 520 Principles of Programming Languages

CSc 520 Principles of Programming Languages 9: Scheme Metacircular Interpretation Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona Copyright c 2005 Christian

### CS61A Midterm 2 Review (v1.1)

Spring 2006 1 CS61A Midterm 2 Review (v1.1) Basic Info Your login: Your section number: Your TA s name: Midterm 2 is going to be held on Tuesday 7-9p, at 1 Pimentel. What will Scheme print? What will the

### An Explicit Continuation Evaluator for Scheme

Massachusetts Institute of Technology Course Notes 2 6.844, Spring 05: Computability Theory of and with Scheme February 17 Prof. Albert R. Meyer revised March 3, 2005, 1265 minutes An Explicit Continuation

### Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper

### Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

### An Explicit-Continuation Metacircular Evaluator

Computer Science (1)21b (Spring Term, 2018) Structure and Interpretation of Computer Programs An Explicit-Continuation Metacircular Evaluator The vanilla metacircular evaluator gives a lot of information

### 6.001: Structure and Interpretation of Computer Programs

6.001: Structure and Interpretation of Computer Programs Symbols Quotation Relevant details of the reader Example of using symbols Alists Differentiation Data Types in Lisp/Scheme Conventional Numbers

### Functional Programming Languages (FPL)

Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 17: Functional Programming Zheng (Eddy Zhang Rutgers University April 4, 2018 Class Information Homework 6 will be posted later today. All test cases

### CSCI337 Organisation of Programming Languages LISP

Organisation of Programming Languages LISP Getting Started Starting Common Lisp \$ clisp i i i i i i i ooooo o ooooooo ooooo ooooo I I I I I I I 8 8 8 8 8 o 8 8 I \ `+' / I 8 8 8 8 8 8 \ `-+-' / 8 8 8 ooooo

### This exam is worth 70 points, or about 23% of your total course grade. The exam contains 15 questions.

CS 61A Final Exam May 16, 2008 Your name login: cs61a This exam is worth 70 points, or about 23% of your total course grade. The exam contains 15 questions. This booklet contains 18 numbered pages including

### University of Massachusetts Lowell

University of Massachusetts Lowell 91.301: Organization of Programming Languages Fall 2002 Quiz 1 Solutions to Sample Problems 2 91.301 Problem 1 What will Scheme print in response to the following statements?

### CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

### Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

### Symbolic Programming. Dr. Zoran Duric () Symbolic Programming 1/ 89 August 28, / 89

Symbolic Programming Symbols: +, -, 1, 2 etc. Symbolic expressions: (+ 1 2), (+ (* 3 4) 2) Symbolic programs are programs that manipulate symbolic expressions. Symbolic manipulation: you do it all the

### C311 Lab #3 Representation Independence: Representation Independent Interpreters

C311 Lab #3 Representation Independence: Representation Independent Interpreters Will Byrd webyrd@indiana.edu February 5, 2005 (based on Professor Friedman s lecture on January 29, 2004) 1 Introduction

### CS450 - Structure of Higher Level Languages

Spring 2018 Streams February 24, 2018 Introduction Streams are abstract sequences. They are potentially infinite we will see that their most interesting and powerful uses come in handling infinite sequences.

### More Scheme CS 331. Quiz. 4. What is the length of the list (()()()())? Which element does (car (cdr (x y z))) extract from the list?

More Scheme CS 331 Quiz 1. What is (car ((2) 3 4))? (2) 2. What is (cdr ((2) (3) (4)))? ((3)(4)) 3. What is (cons 2 (2 3 4))? (2 2 3 4) 4. What is the length of the list (()()()())? 4 5. Which element

### INTRODUCTION TO SCHEME

INTRODUCTION TO SCHEME PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2019 Dalhousie University 1/110 SCHEME: A FUNCTIONAL PROGRAMMING LANGUAGE Functions are first-class values: Can be passed as

### Overview. CS301 Session 3. Problem set 1. Thinking recursively

Overview CS301 Session 3 Review of problem set 1 S-expressions Recursive list processing Applicative programming A look forward: local variables 1 2 Problem set 1 Don't use begin unless you need a side

### Scheme as implemented by Racket

Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

### SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

### CS 314 Principles of Programming Languages. Lecture 16

CS 314 Principles of Programming Languages Lecture 16 Zheng Zhang Department of Computer Science Rutgers University Friday 28 th October, 2016 Zheng Zhang 1 CS@Rutgers University Class Information Reminder:

### Scheme: Expressions & Procedures

Scheme: Expressions & Procedures CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, March 31, 2017 Glenn G. Chappell Department of Computer Science University

### ;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for

Page 1/11 (require (lib "trace")) Allow tracing to be turned on and off (define tracing #f) Define a string to hold the error messages created during syntax checking (define error msg ""); Used for fancy

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 18: Functional Programming Zheng (Eddy) Zhang Rutgers University April 9, 2018 Review: Defining Scheme Functions (define ( lambda (

### CSE 341 Section Handout #6 Cheat Sheet

Cheat Sheet Types numbers: integers (3, 802), reals (3.4), rationals (3/4), complex (2+3.4i) symbols: x, y, hello, r2d2 booleans: #t, #f strings: "hello", "how are you?" lists: (list 3 4 5) (list 98.5

### Chapter 15 Functional Programming Languages

Chapter 15 Functional Programming Languages Fundamentals of Functional Programming Languages Introduction to Scheme A programming paradigm treats computation as the evaluation of mathematical functions.

### Project 2: Scheme Interpreter

Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same

### Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme

### CPS 506 Comparative Programming Languages. Programming Language Paradigm

CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming

### Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP)

Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP) Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology

### TAIL RECURSION, SCOPE, AND PROJECT 4 11

TAIL RECURSION, SCOPE, AND PROJECT 4 11 COMPUTER SCIENCE 61A Noveber 12, 2012 1 Tail Recursion Today we will look at Tail Recursion and Tail Call Optimizations in Scheme, and how they relate to iteration

### Programming Languages. Function-Closure Idioms. Adapted from Dan Grossman's PL class, U. of Washington

Programming Languages Function-Closure Idioms Adapted from Dan Grossman's PL class, U. of Washington More idioms We know the rule for lexical scope and function closures Now what is it good for A partial

### Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004

Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004 CS 314, LS,BR,LTM: Scope and Memory 1 Review Functions as first-class objects What can you do with an integer?

### SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

SCHEME 0 COMPUTER SCIENCE 6A July 26, 206 0. Warm Up: Conditional Expressions. What does Scheme print? scm> (if (or #t (/ 0 (/ 0 scm> (if (> 4 3 (+ 2 3 4 (+ 3 4 (* 3 2 scm> ((if (< 4 3 + - 4 00 scm> (if

### CS 480. Lisp J. Kosecka George Mason University. Lisp Slides

CS 480 Lisp J. Kosecka George Mason University Lisp Slides Symbolic Programming Symbols: +, -, 1, 2 etc. Symbolic expressions: (+ 1 2), (+ (* 3 4) 2) Symbolic programs are programs that manipulate symbolic

### CSE 413 Midterm, May 6, 2011 Sample Solution Page 1 of 8

Question 1. (12 points) For each of the following, what value is printed? (Assume that each group of statements is executed independently in a newly reset Scheme environment.) (a) (define x 1) (define

### Principles of Programming Languages

Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 6 - Defining a Programming Language Bottom Up Collaboration and Management - Elements of Programming Dana Fisman 1 What we accomplished

### User-defined Functions. Conditional Expressions in Scheme

User-defined Functions The list (lambda (args (body s to a function with (args as its argument list and (body as the function body. No quotes are needed for (args or (body. (lambda (x (+ x 1 s to the increment

### Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP)

Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP) Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology

### CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan 1 Reading SICP, page 11-19, Section 1.1.6 Little Schemer, Chapter 2 2 The Idea of Syntax Abstraction Problem. Often programming tasks are repetitive,

### Functional programming with Common Lisp

Functional programming with Common Lisp Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 81 Expressions and functions

### Principles of Programming Languages 2017W, Functional Programming

Principles of Programming Languages 2017W, Functional Programming Assignment 3: Lisp Machine (16 points) Lisp is a language based on the lambda calculus with strict execution semantics and dynamic typing.

### Evaluating Scheme Expressions

Evaluating Scheme Expressions How Scheme evaluates the expressions? (procedure arg 1... arg n ) Find the value of procedure Find the value of arg 1 Find the value of arg n Apply the value of procedure

### Procedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt

Data abstractions Abstractions and their variations Basic data abstractions Why data abstractions are useful Procedural abstraction Process of procedural abstraction Define formal parameters, capture process

### Essentials of Programming Languages Language

Essentials of Programming Languages Language Version 5.3 August 6, 2012 The Essentials of Programming Languages language in DrRacket provides a subset of functions and syntactic forms of racket mostly

### Essentials of Programming Languages Language

Essentials of Programming Languages Language Version 6.90.0.26 April 20, 2018 The Essentials of Programming Languages language in DrRacket provides a subset of functions and syntactic forms of racket mostly

### Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work

### Syntactic Sugar: Using the Metacircular Evaluator to Implement the Language You Want

Computer Science 21b (Spring Term, 2017) Structure and Interpretation of Computer Programs Syntactic Sugar: Using the Metacircular Evaluator to Implement the Language You Want Here is one of the big ideas

### CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018

CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018 Deliverables: Your code (submit to PLC server). A13 participation survey (on Moodle, by the day after the A13 due date). This is

### Racket: Modules, Contracts, Languages

Racket: Modules, Contracts, Languages Advanced Functional Programming Jean-Noël Monette November 2013 1 Today Modules are the way to structure larger programs in smaller pieces. Modules can import and