# CSCC24 Functional Programming Scheme Part 2

Size: px
Start display at page:

Transcription

1 CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1

2 The Spirit of Lisp-like Languages We shall first define a class of symbolic expressions in terms of ordered pairs and lists. Then we shall define five elementary functions and predicates, and build from them by composition, conditional expressions and recursive definitions an extensive class of functions of which we shall give a number of examples. We shall then show how these functions can themselves be expressed as symbolic expressions, and we shall give a universal function apply that allows us to compute from the expressions for a given function its value for given arguments. Finally, we shall define some functions with functions as arguments and give some useful examples. McCarthy, J, [1960]. Recursive functions of symbolic expressions and their computation by machine, Part I. Comm. ACM 3:4; 2

3 The story so far... We learned a bit about the properties of Scheme and other Lisp dialects (and we will revisit this soon) We talked a bit about lists in scheme They re constructed from pairs, also known as cons pairs, other than the empty list They took advantage of a specific half-register instruction set to efficiently implement linked lists They are the building block of Scheme And, we ve started learning a little about Scheme We re using the pure functional subset - no side effects, denotational semantics, static scoping Data types overview A Scheme expression - it s a value, or we compute its value in a specific way Read - Evaluate - Print loop Finally, we ve talked a bit about recursion and tail recursion 3

4 Review Questions What does it mean that a functional language has no side effects? Can you explain recursion? How are lists constructed in Scheme? How is Scheme executed? What forms can a Scheme expression have? How is writing a program different in Scheme than in Python? What makes a problem easy to solve with a tail-recursive solution? Could you come up with a grammar for the syntax of Scheme? Can we implement every iterative algorithm recursively? As an aside - you may need to try to solve problems on your own to really understand Scheme and functional programming. Spend a little time working on problems. 4

5 Recall: In pure functional programming languages, recursion is generally preferred as a matter of style to iterative constructs like while-loops or for-loops. This makes programs easier to prove correct, easier to conceptualize as functions: Try - how do you directly translate a recursive algorithm into an iterative one? An iterative one into a recursive one? What method do you think we use to prove recursive algorithms correct? 5

6 Structural recursion Structural recusion means we take advantage of a data type s recursive structure to traverse it and perform some operation. (define my-func (lambda (lst) (cond ((empty? lst)... ) (else... (first lst)... (my-func (rest lst))... )))) 6

7 Linear recursion There is at most one recursive call made in any execution of function body. Useful when repeating an operation n times (Recall n! for example) 7

8 Tail-recursion The recursive call is in the last function application in function body. Tail-recursion is implemented very efficiently and should be used whenever possible. It is not necessary to save a stack frame if the control flow of the program will never return to that function context. Some problems are naturally tail-recursive. More often, we ll need to use an accumulator or some sort, and a helper function. Recall the tail-recursive version of factorial from last class. 8

9 Recursion Flat recursion: recursion applied over top items of a list. Deep recursion: (aka tree recursion) recursion applied over all items. Mutual recursion: functions call each other, rather that themselves. 9

10 Mutual recursion example (define even (lambda (lst) (cond ((empty? lst) empty) (else (cons (first lst) (odd (rest lst))))))) (define odd (lambda (lst) (cond ((empty? lst) empty) (else (even (rest lst)))))) Question - What does this code do? 10

11 Variable Arity Functions We have declared functions with this syntax: (define <identifier> (lambda (a1 a2...an) <expression>)) That list of arguments can be treated as any other Scheme list, for example: (define <identifier> (lambda lst <expression>) Example - sum of squares version 1 11

12 Higher-order functions In Python, we have a glimpse of some of the ideas we will be using. Consider the following code snippet: mylist = [1, 2, 3, 4, 5, 6] newlist = [] for item in mylist: newlist = newlist + [item * item] 12

13 Higher-order functions In Python, we have a glimpse of some of the ideas we will be using. Consider the following code snippet: mylist = [1, 2, 3, 4, 5, 6] newlist = [] for item in mylist: newlist = newlist + [item * item] newlist will be the list [1, 4, 9, 16, 25, 36] 12

14 Higher-order functions In Python, we have a glimpse of some of the ideas we will be using. Consider the following code snippet: mylist = [1, 2, 3, 4, 5, 6] newlist = [] for item in mylist: newlist = newlist + [item * item] newlist will be the list [1, 4, 9, 16, 25, 36] What does that tell us about for loops in Python? 12

15 Higher-order functions In Python, we have a glimpse of some of the ideas we will be using. Consider the following code snippet: mylist = [1, 2, 3, 4, 5, 6] newlist = [] for item in mylist: newlist = newlist + [item * item] newlist will be the list [1, 4, 9, 16, 25, 36] What does that tell us about for loops in Python? These loops use an iterator. They iterate in order, through this list. 12

16 higher order functions But is this necesary? Do we really need to compute these squares one at a time in this order? What if we re doing something far more complicated, and we have a supercomputer or a cluster at our disposal? We can revisit a function you may have met in Python to illustrate, map, and we ll use the python lambda function mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] squares = map(lambda item: item*item, mylist) Question - Does the Python map function still iterate over the items one at a time? If an iterative implementation of map was replaced by a parallel one with arbitrary order of execution, would it matter? 13

17 higher order functions Python, C and Java have other constructs that use higher order functions, directly or indirectly. For example: Template classes Function pointers List constructors 14

18 higher order functions We ll move into how this works in Scheme, and look at how this gives us a model for breaking down problems into parallelizable chunks. But first we can step back and look at the concept in general. 15

19 higher-order functions A higher order function takes a function (or functions) as input values. Consider the similarity between these functions: ;; (all-odd lst) return #t if every element of lst is odd ;; Pre: lst is a list of numbers (define all-odd (lambda (lst) (if (empty? lst) #t (and (odd? (first lst)) (all-odd (rest lst)))))) ;; (all-even lst) return #t if every elt of lst is even ;; Pre: lst is a list of numbers (define all-even (lambda (lst) (if (empty? lst) #t (and (even? (first lst)) (all-even (rest lst)))))) 16

20 higher-order functions We can use a function as an values, and make a general testing function: ;; (all-test test lst) return #t if test is true of ;; every element of lst ;; Pre: lst is a list ;; test is a predicate procedure applicable to ;; every element of lst (define all-test (lambda (test lst) (if (empty? lst) #t (and (test (first lst)) (all-test (rest lst)))))) 17

21 higher-order functions Functions can also be the return value of another function: ;; (make-proc f g) return a composition f o g ( or g(f(x)) ;; Pre: the composition f o g is well-defined What would (make-proc + square) return? How would you implement this? 18

22 higher-order functions: map We can use the Scheme function map like we did the Python map function: take two arguments: a function and a list. build a new list whose elements are the result of applying the function to each element of the (old) list. (define mylist ( )) (map (lambda (item) (* item item)) mylist) > ( ) The built-in map is more general and more powerful. 19

23 (map proc l1 l2... higher-order functions: map ln) proc : an n-ary procedure l1 l2... ln : lists of length m apply proc element-wise to elements of l1 l2... ln return the list of results (e1 e2... em) the order of evaluation is unspecified: appears to be evaluated in parallel 20

24 (map proc l1 l2... higher-order functions: map ln) (map abs ( ) ==> ( ) (map max (1 2 3) (0 5 42)) ==> (1 5 42) (map + (1 2 3) (2 3 4) (3 4 5)) ==> (6 9 12) (map cons (a b c) ((a a) (b b) (c c))) ==> ((a a a) (b b b) (c c c)) (map (lambda (x) (+ x 1)) (1 2 3)) ==> (2 3 4) (map (lambda (x y) (+ 1 (- y x))) (0 5 10) (1 5 11)) ==> (2 1 2) 21

25 Scheme review Before we continue, let s review the syntax and semantics of Scheme that we ve learned so far: Scheme is made up of expressions, which can be build up according to out grammar. <Expr> ::= <Value> They can be made of different data types: Lists - constructed from pairs, sometimes known as cons pairs. Numbers - multiple numeric types in a heirarchy Symbols - Letters or identifiers. Functions - a first class kind of value in Scheme 22

26 Scheme review Expressions can also be of other forms: <expr> ::= <function call> <lambda expression> <conditional> <definition> <let macro> (Note: This is not quite a formal grammar of Scheme - why?) 23

27 Function calls Scheme review <function call> ::= ( < Function ID> {<Argument>}+) 24

28 Lamda expression Scheme review <lambda expression> ::= ( lambda <Arg List> <expr> ) 25

29 Conditional Scheme review <conditional> ::= ( cond (<bool expr> <expr>) (<bool expr> <expr>)... (else <expr>)) 26

30 Definition Scheme review <definition> ::= (define <ID> <Expr>) 27

31 Let statements - syntactic sugar We re missing one useful Scheme construct from this list - the let expressions. These are syntactic sugar - they can be changed to a different form without evaluation. However, they can make your code clearer, and you should use them where applicable. 28

32 versions of let (let ([var1 expr1]... [varn exprn]) body) Create local variables and bind them to expression results. The scope of these variables is the body of the let statement. Evaluation: expr1,..., exprn are evaluated in some undefined order, saved, and then assigned to var1,..., varn. In our interpreter, they have the appearance of being evaluated in parallel. 29

33 Consider: versions of let (define sq-cube (lambda (x) (let ([sqr (* x x)] [cube (* x (* x x))]) (list sqr cube)))) Want to reuse sqr. 30

34 Want to reuse sqr. versions of let (define sq-cube (lambda (x) (let ([sqr (* x x)] [cube (* x sqr)]) (list sqr cube)))) But this does not work - why? 31

35 versions of let (let* ([var1 expr1]... [varn exprn]) body) The scope of each variable is the part of the let*-expression to the right of the binding. Evaluation: expr1,..., exprn are evaluated sequentially, from left to right. 32

36 Use let*: versions of let (define sq-cube (lambda (x) (let* ([sqr (* x x)] [cube (* x sqr)]) (list sqr cube)))) 33

37 versions of let (letrec ([var1 expr1]... [varn exprn]) body ) Scope: Each binding of a variable has the entire letrec expression as its region. Evaluation: expr1,..., exprn are evaluated in an undefined order, saved, and then assigned to var1,..., varn, with the appearance of being evaluated in parallel. 34

38 versions of let ;; (length lst) returns the length of lst ;; Pre: lst is a list (define length (lambda (lst) (letrec ([length-tail (lambda (lst len) (if (empty? lst) len (length-tail (rest lst) (+ len 1))))]) (length-tail lst 0)))) 35

39 (let ([x 2]) (* x x)) versions of let (let ([x 4]) (let ([y (+ x 2)]) (* x y))) (let ([x 4] [y (+ x 2)]) (* x y)) (let* ([x 4] [y (+ x 2)]) (* x y)) 36

40 (let ([x 2]) (* x x)) 4 versions of let (let ([x 4]) (let ([y (+ x 2)]) (* x y))) 24 (let ([x 4] [y (+ x 2)]) (* x y)) is an error: unbound variable x (let* ([x 4] [y (+ x 2)]) (* x y)) 24 37

41 versions of let (let ((v1 e1)...(vn en)) expr) ((lambda (v1...vn) expr) e1...en) AND (let* ((v1 e1) (v2 e2)) expr) ((lambda (v1) ((lambda (v2) expr) e2)) e1) All binding of values to variables is by parameter passing ( lambda reduction): no assignment 38

42 higher-order functions: apply (apply op lst) op : an n-ary procedure lst : list of n arguments to op apply op to elements of lst return result of evaluation 39

43 (apply op lst) higher-order functions: apply (apply + ( )) ( ) 10 (apply cons (a (b c))) (cons a (b c)) (a b c) (apply list ( )) (list ) ( ) (apply cons (a (b c) (d))) (cons a (b c) (d)) Error 40

44 higher-order functions: fold (foldr op id lst) op : an binary procedure lst : list of arguments apply op right-associatively to elements of lst return result of evaluation the identity element id is always used That is: (foldr op id ()) id (foldr op id (e)) (op e id) (foldr op id (e1 e2... en)) (op e1 (op e2 (op... (op en id)))) 41

45 higher-order functions: foldr Let s implement a version, myfoldr 42

46 higher-order functions: foldr (foldr list () ( )) (1 (2 (3 (4 ())))) (myfoldr list () ( )) (list 1 (myfoldr list () (2 3 4))) (list 1 (list 2 (myfoldr list () (3 4)))) (list 1 (list 2 (list 3 (myfoldr list () (4))))) (list 1 (list 2 (list 3 (list 4 (myfoldr list () ()))))) (list 1 (list 2 (list 3 (list 4 ())))) (list 1 (list 2 (list 3 (4 ())))) (list 1 (list 2 (3 (4 ())))) (list 1 (2 (3 (4 ())))) (1 (2 (3 (4 ())))) 43

47 (foldr op id lst) op cons id () higher-order functions: foldr ( ) => (cons 1 (cons 2 (cons 3 (cons 4 ())))) ( + 1 ( + 2 ( + 3 ( )))) => (foldr + 0 ( ) (list 1 (list 2 (list 3 (list 4 ())))) => (foldr list () ( ) 44

48 higher-order functions: foldl (foldl op id lst) op : an binary procedure lst : list of arguments apply op left-associatively to elements of lst return result of evaluation the identity element id is always used That is: (foldl op id ()) id (foldl op id (e)) (op id e) (foldl op id (e1 e2... en)) (op... (op (op id e1) e2)...) en ) 45

49 higher-order functions: foldl (foldl op id lst) In other implementations: (foldl op id ()) id (foldl op id (e)) (op id e) (foldl op id (e1 e2... en)) (op en (op en-1 (op... (op e1 id)))) 46

50 (foldr op id lst) op cons id () higher-order functions: foldr (define (append list1 list2) (define (map p lst) 47

51 higher-order functions: foldr (append ( ) (5 6 7)) => (foldr cons (5 6 7) ( )) => (cons 1 (foldr cons (5 6 7) (2 3 4))) => (cons 1 (cons 2 (foldr cons (5 6 7) (3 4)))) => (cons 1 (cons 2 (cons 3 (foldr cons (5 6 7) (4))))) => (cons 1 (cons 2 (cons 3 (cons 4 (foldr cons (5 6 7) ()))))) <= (cons 1 (cons 2 (cons 3 (cons 4 (5 6 7))))) = (cons 1 (cons 2 (cons 3 ( )))) = (cons 1 (cons 2 ( ))) = (cons 1 ( )) = ( ) 48

52 higher-order functions: foldr (map abs (-1 2-3)) => (foldr (lambda (x r) (cons (abs x) r)) () (-1 2-3)) => ((lambda (x r) (cons (abs x) r)) -1 (foldr (lambda (x r) (cons (abs x) r)) () (2-3))) => ((lambda (x r) (cons (abs x) r)) -1 ((lambda (x r) (cons (abs x) r)) 2 (foldr (lambda (x r) (cons (abs x) r)) () (-3)))) 49

53 higher-order functions: foldr => ((lambda (x r) (cons (abs x) r)) -1 ((lambda (x r) (cons (abs x) r)) 2 ((lambda (x r) (cons (abs x) r)) -3 (foldr (lambda (x r) (cons (abs x) r)) () ())))) <= ((lambda (x r) (cons (abs x) r)) -1 ((lambda (x r) (cons (abs x) r)) 2 ((lambda (x r) (cons (abs x) r)) -3 ()))) 50

54 higher-order functions: foldr = ((lambda (x r) (cons (abs x) r)) -1 ((lambda (x r) (cons (abs x) r)) 2 (cons (abs -3) ()))) = ((lambda (x r) (cons (abs x) r)) -1 ((lambda (x r) (cons (abs x) r)) 2 (3))) = ((lambda (x r) (cons (abs x) r)) -1 (cons (abs 2) (3))) = ((lambda (x r) (cons (abs x) r)) -1 (2 3)) = (cons (abs -1) (2 3)) = (1 2 3) 51

55 Scheme Review We now know all the syntax we will need in Scheme, and we can summarize the functions we know. Everything else can be implemented from this basic set of functions - indeed, we don t even need all of these. Number related functions: =, +, -, *, number? List and symbol related functions: list?, empty?, first, rest, cons, append, list, eq? Higher order functions map, foldr, foldl, fold, apply Other quote/, eval 52

56 Review Questions How does the Scheme or Python map function differ from a Python for item in list: loop? How are functions values in Scheme? Why should we use tail recursion when possible? Create an ambiguous grammar for code comments /* delimited like so */, then create an unambiguous one. What does it mean that Scheme has no side-effects? Create a tail-recursive function to compute the nth number the fibonacci series. What is the difference between syntax and semantics? What is the difference between denotational and operational semantics? Can you implement append with just the cons function? 53

57 Consider: FP and Formal Proofs if op is commutative, then (foldr op id lst) = (foldl op id lst) for all op, id, lst. is it true? how would one prove it? 54

58 FP and Formal Proofs (define len (lambda (lst) (if (empty? lst)) 0 (+ 1 (len (rest lst))))) and (define append (lambda (lst1 lst2) (if (empty? lst1)) lst2 (cons (first lst1) (append (rest lst1) lst2)))) Prove: for all lists l1, l2 (len (append l1 l2)) = (+ (len l1) (len l2)) 55

59 FP and Formal Proofs Need to establish some axioms / facts first: If lst is a list then 1. lst = (), or 2. exist element X and list Y, s.t. lst = (cons X Y) 56

60 FP and Formal Proofs Need to establish some axioms / facts first: 0. (define len 1. (lambda (lst) 2. (if (empty? lst)) (+ 1 (len (rest lst))))) [1] (len ()) = 0 [lines 2,3] [2] (len (cons X Y)) = (+ 1 (len Y)) [lines 2,4] 57

61 FP and Formal Proofs Need to establish some axioms / facts first: 0. (define append 1. (lambda (lst1 lst2) 2. (if (empty? lst1)) 3. lst2 4. (cons (first lst1) 5. (append (rest lst1) lst2)))) [3] (append () l2) = l2 [lines 2,3] [4] (append (cons X Y) l2) = (cons X (append Y l2)) [lines 2-5] 58

62 FP and Formal Proofs Now, given that If lst is a list then 1. lst = (), or 2. exist element X and list Y, s.t. lst = (cons X Y) and the following four facts: [1] (len ()) = 0 [2] (len (cons X Y)) = (+ 1 (len Y)) [3] (append () l2) = l2 [4] (append (cons X Y) l2) = (cons X (append Y l2)) and assuming + performs correct addition, prove: for all lists l1, l2 (len (append l1 l2)) = (+ (len l1) (len l2)) 59

63 Recursion Induction prove: for all lists l1, l2 (len (append l1 l2)) = (+ (len l1) (len l2)) Proof by structural induction on the list l1. Case: [l1 is ()] (len (append l1 l2)) = (len (append () l2)) [case] = (len l2) [3] = (+ 0 (len l2)) [arith] = (+ (len ()) (len l2)) [1] = (+ (len l1) (len l2)) [case] 60

64 Recursion Induction prove: for all lists l1, l2 (len (append l1 l2)) = (+ (len l1) (len l2)) Case: [l1 = (cons X Y)] IH: Assume (len (append Y l2)) = (+ (len Y) (len l2)) (len (append l1 l2)) = (len (append (cons X Y) l2)) [case] = (len (cons X (append Y l2))) [4] = (+ 1 (len (append Y l2))) [2] = (+ 1 (+ (len Y) (len l2))) [IH] = (+ (+ 1 (len Y)) (len l2)) [arith] = (+ (len (cons X Y)) (len l2)) [2] = (+ (len l1) (len l2)) [case] 61

65 parameter lists bind a formal parameter to a list of actual parameters (define list-args (lambda varparam varparam)) (list-args) ==> () (list-args a) ==> (a) (list-args a b c d) ==> (a b c d) 62

66 parameter lists bind a formal parameter to a list of actual parameters (define rev-args (lambda varparam (reverse varparam))) (rev-args ) ==> () (rev-args a b c) ==> (c b a) (rev-args ) ==> ( ) 63

67 parameter lists bind a formal parameter to a list of actual parameters (define sum-non1-args (lambda (fst. varparam) (apply + varparam))) (sum-non1-args 1) ==> 0 (sum-non1-args 1 2) ==> 2 (sum-non1-args 1 2 3) ==> 5 (sum-non1-args ) ==> Error: requires at least 1 argument 64

68 parameter lists bind a formal parameter to a list of actual parameters (define sum-non12-args (lambda (fst sec. varparam) (apply + varparam))) (sum-non12-args 1 2) ==> 0 (sum-non12-args ) ==> 7 (sum-non12-args 1) ==> Error: requires at least 2 arguments 65

69 pure functional languages Programs are viewed as collections of functions. Execution of programs is viewed as evaluation. 66

70 pure functional languages Referential transparency: The value of a function application is independent of the context in which it occurs. A language is referentially transparent if we may replace one expression with another of equal value anywhere in a program without changing the meaning of the program. Value of f(a,b,c) depends only on the values of f, a, b and c. It does not depend on the global state of computation. 67

71 pure functional languages Referential transparency: Main advantage: facilitates reasoning about programs and applying program transformations. Aside: Referential transparency is no longer considered a distinguishing feature of functional programming languages. It arguably holds in well-designed imperative languages too. See Mitchell, page 78 for further discussion. 68

72 pure functional languages Manifest Interface Principle: All interfaces are apparent in syntax. Code is then more modular, arguments are interface(s). 69

73 pure functional languages No assignment statement: A variable may not have a value, or its value might be a function that has not been applied to its arguments yet, but variables in pure FP are said to be logical in that, having acquired a value in the course of an evaluation, they retain that value until the end of evaluation. This is similar to the manner in which variables are used in mathematics. Remember when you had to unlearn your mathematics training to make sense of x := x+1? In FP, this is anathema! 70

74 No side effects: pure functional languages Function calls have no side effects. No need to consider global state. Programs are easier to reason about. Programs are easier to prove correct. Historically, imperative programming had to refer to Turing machines to talk about state, however there are very good techniques now. 71

75 pure functional languages Functions are first-class values: Can be returned as the value of an expression. Can be passed as an argument. Can be put in a data structure as a value. Unnamed functions exist as values. 72

76 recursion vs. iteration: pure functional languages In pure FP, recursion is generally preferred as a matter of style to iterative constructs like while-loops or for-loops. This makes programs easier to prove correct, easier to conceptualize as functions: Recursions, like functions, identify the structure of one or more arguments as the only values upon which the computation (and termination) depends. 73

77 a higher-level language: pure functional languages All storage management is implicit: we don t have to think about how program state maps to a computer s memory (or at least, not until we want to write super-efficient code). That means no assignment, no new/free calls to manage our own memory, and no pointers. The state of a computation is much easier to think about. 74

### CSC324 Functional Programming Efficiency Issues, Parameter Lists

CSC324 Functional Programming Efficiency Issues, Parameter Lists Afsaneh Fazly 1 January 28, 2013 1 Thanks to A.Tafliovich, P.Ragde, S.McIlraith, E.Joanis, S.Stevenson, G.Penn, D.Horton 1 Example: efficiency

### 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

### Introduction to Functional Programming in Racket. CS 550 Programming Languages Jeremy Johnson

Introduction to Functional Programming in Racket CS 550 Programming Languages Jeremy Johnson 1 Objective To introduce functional programming in racket Programs are functions and their semantics involve

### 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

### 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,

### 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).

### 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

### 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 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 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

### Functional Programming - 2. Higher Order Functions

Functional Programming - 2 Higher Order Functions Map on a list Apply Reductions: foldr, foldl Lexical scoping with let s Functional-11, CS5314, Sp16 BGRyder 1 Higher Order Functions Functions as 1st class

### 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,

### 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

### Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

Racket Next 2+ weeks will use the Racket language (not ML) and the DrRacket programming environment (not emacs) Installation / basic usage instructions on course website CSE34: Programming Languages Lecture

### 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

### SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

SCHEME COMPUTER SCIENCE 6A October 29th, 202 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, we will eventually

### Intro. Scheme Basics. scm> 5 5. scm>

Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

### 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

### 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

### 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 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,

### 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

### 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

### 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 and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming

### Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

### Functional abstraction

Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

### 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

### Introduction to Functional Programming in Haskell 1 / 56

Introduction to Functional Programming in Haskell 1 / 56 Outline Why learn functional programming? The essence of functional programming What is a function? Equational reasoning First-order vs. higher-order

### 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

### 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

### 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

### CS115 - Module 9 - filter, map, and friends

Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Intermezzo 3 (Section 18); Sections 19-23. Abstraction abstraction, n. 3a.... The process of isolating properties or

### 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

### 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

### Programming Languages Third Edition

Programming Languages Third Edition Chapter 12 Formal Semantics Objectives Become familiar with a sample small language for the purpose of semantic specification Understand operational semantics Understand

### CS115 - Module 10 - General Trees

Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Sections 15 and 16. Arithmetic Expressions Recall with binary trees we could represent an expression containing binary

### 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

### INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

INTERPRETERS 8 COMPUTER SCIENCE 61A November 3, 2016 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that understand other programs. In

### 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

### A Small Interpreted Language

A Small Interpreted Language What would you need to build a small computing language based on mathematical principles? The language should be simple, Turing equivalent (i.e.: it can compute anything that

### 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

### 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

### 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

### Programming Language Pragmatics

Chapter 10 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken Alan Turing, Alonzo Church, Stephen

### 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

### An Introduction to Scheme

An Introduction to Scheme Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Stéphane Ducasse 1 Scheme Minimal Statically scoped Functional Imperative Stack manipulation Specification

### Chapter 11 :: Functional Languages

Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Copyright 2016 Elsevier 1 Chapter11_Functional_Languages_4e - Tue November 21, 2017 Historical Origins The imperative

### 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

### 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

### 6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

### 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,

### Basic Scheme February 8, Compound expressions Rules of evaluation Creating procedures by capturing common patterns

Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns Previous lecture Basics of Scheme Expressions and associated values (or syntax and

### CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

### CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Basics

1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Basics 2 Contents 1. Jump into Haskell: Using ghc and ghci (more detail) 2. Historical Background of Haskell 3. Lazy, Pure, and Functional

### INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing Common Lisp Fundamentals Stephan Oepen & Murhaf Fares Language Technology Group (LTG) August 30, 2017 Last Week: What is

### A Brief Introduction to Scheme (I)

A Brief Introduction to Scheme (I) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Scheme Scheme I p.1/44 Scheme: Feature Set A

### Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Processadors de Llenguatge II Functional Paradigm Pratt A.7 Robert Harper s SML tutorial (Sec II) Rafael Ramirez Dep Tecnologia Universitat Pompeu Fabra Paradigm Shift Imperative Paradigm State Machine

### 6.001 Notes: Section 6.1

6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of

### 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

### CMSC 330: Organization of Programming Languages. Operational Semantics

CMSC 330: Organization of Programming Languages Operational Semantics Notes about Project 4, Parts 1 & 2 Still due today (7/2) Will not be graded until 7/11 (along with Part 3) You are strongly encouraged

### MetacircularScheme! (a variant of lisp)

MetacircularScheme! (a variant of lisp) Lisp = Beauty Passed on through ages Basic Expressions (function arg1 arg2 ) To evaluate an expression, apply the functionto the arguments. (+ 1 2)? => 3 (sqrt4)?

### Principles of Programming Languages

Principles of Programming Languages Lesson 14 Type Checking Collaboration and Management Dana Fisman www.cs.bgu.ac.il/~ppl172 1 Type Checking We return to the issue of type safety we discussed informally,

### Lambda Calculus. Gunnar Gotshalks LC-1

Lambda Calculus LC-1 l- Calculus History Developed by Alonzo Church during 1930 s-40 s One fundamental goal was to describe what can be computed. Full definition of l-calculus is equivalent in power to

### 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

### 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

### CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

### Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

CS 61A Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that

### CS 242. Fundamentals. Reading: See last slide

CS 242 Fundamentals Reading: See last slide Syntax and Semantics of Programs Syntax The symbols used to write a program Semantics The actions that occur when a program is executed Programming language

### Streams and Evalutation Strategies

Data and Program Structure Streams and Evalutation Strategies Lecture V Ahmed Rezine Linköpings Universitet TDDA69, VT 2014 Lecture 2: Class descriptions - message passing ( define ( make-account balance

### CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise

CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise If you re not already crazy about Scheme (and I m sure you are), then here s something to get

### 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

### JVM ByteCode Interpreter

JVM ByteCode Interpreter written in Haskell (In under 1000 Lines of Code) By Louis Jenkins Presentation Schedule ( 15 Minutes) Discuss and Run the Virtual Machine first

### 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

### 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

### 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

### Denotational Semantics. Domain Theory

Denotational Semantics and Domain Theory 1 / 51 Outline Denotational Semantics Basic Domain Theory Introduction and history Primitive and lifted domains Sum and product domains Function domains Meaning

### Lists in Lisp and Scheme

Lists in Lisp and Scheme a Lists in Lisp and Scheme Lists are Lisp s fundamental data structures, but there are others Arrays, characters, strings, etc. Common Lisp has moved on from being merely a LISt

### 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

### Lambda Calculus and Lambda notation in Lisp II. Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky.

λ Calculus Basis Lambda Calculus and Lambda notation in Lisp II Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky Mathematical theory for anonymous functions» functions that have

### 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

### Contents. Chapter 1 SPECIFYING SYNTAX 1

Contents Chapter 1 SPECIFYING SYNTAX 1 1.1 GRAMMARS AND BNF 2 Context-Free Grammars 4 Context-Sensitive Grammars 8 Exercises 8 1.2 THE PROGRAMMING LANGUAGE WREN 10 Ambiguity 12 Context Constraints in Wren

### Homework 1. Notes. What To Turn In. Unix Accounts. Reading. Handout 3 CSCI 334: Spring, 2017

Homework 1 Due 14 February Handout 3 CSCI 334: Spring, 2017 Notes This homework has three types of problems: Self Check: You are strongly encouraged to think about and work through these questions, but

### Types and Static Type Checking (Introducing Micro-Haskell)

Types and Static (Introducing Micro-Haskell) Informatics 2A: Lecture 13 Alex Simpson School of Informatics University of Edinburgh als@inf.ed.ac.uk 16 October, 2012 1 / 21 1 Types 2 3 4 2 / 21 Thus far

### Lambda Calculus see notes on Lambda Calculus

Lambda Calculus see notes on Lambda Calculus Shakil M. Khan adapted from Gunnar Gotshalks recap so far: Lisp data structures basic Lisp programming bound/free variables, scope of variables Lisp symbols,

### Introduction to lambda calculus Part 3

Introduction to lambda calculus Part 3 Antti-Juhani Kaijanaho 2017-01-27... 1 Untyped lambda calculus... 2 Typed lambda calculi In an untyped lambda calculus extended with integers, it is required that

### 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

### CONCEPTS OF PROGRAMMING LANGUAGES Solutions for Mid-Term Examination

COMPUTER SCIENCE 320 CONCEPTS OF PROGRAMMING LANGUAGES Solutions for Mid-Term Examination FRIDAY, MARCH 3, 2006 Problem 1. [25 pts.] A special form is an expression that is not evaluated according to the

### 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,

### by the evening of Tuesday, Feb 6

Homework 1 Due 14 February Handout 6 CSCI 334: Spring 2018 Notes This homework has three types of problems: Self Check: You are strongly encouraged to think about and work through these questions, and

### 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

Programming Languages Lambda Calculus and Scheme CSCI-GA.2110-003 Fall 2011 λ-calculus invented by Alonzo Church in 1932 as a model of computation basis for functional languages (e.g., Lisp, Scheme, ML,

### Programming with Math and Logic

.. Programming with Math and Logic an invitation to functional programming Ed Morehouse Wesleyan University The Plan why fp? terms types interfaces The What and Why of Functional Programming Computing

### 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

### G Programming Languages - Fall 2012

G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter

### Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Haskell: Lists CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks

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: