# Chapter 1. Fundamentals of Higher Order Programming

Size: px
Start display at page:

Transcription

1 Chapter 1 Fundamentals of Higher Order Programming 1

2 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme uses the same syntax for data and procedures. This is known as homoiconicity. 2

3 Expressions, Values & The REPL The Read-Eval-Print Loop Expressions have a value 3

4 Expressions Prefix Notation Primitive Expressions > 4 4 > -5-5 > (* 5 6 ) Combinations 30 > ( ) 20 > (* 4 (* 5 6)) 120 > (* 7 (- 5 4) 8) 56 > (- 6 (/ 12 4) (* 2 (+ 5 6))) -19 Nested Expressions 4

5 Identifiers (aka Variables) At any point in time, Scheme has access to an environment The identifier is bound to a value Welcome to DrRacket, version 5.0 [3m]. Language: scheme; memory limit: 256 MB. > n reference to an identifier before its definition: n > (define n 10) > n 10 > define adds an identifier to the environment In the beginning, there is only a global environment (define <identifier> <expression>) 5

6 Examples Welcome to DrRacket, version 5.0 [3m]. Language: scheme; memory limit: 256 MB. > (define size 2) > (* 5 size) 10 > (define pi ) > (define radius 10) > (* pi (* radius radius)) > (define circumference (* 2 pi radius)) > circumference >... * * + + size pi radius circumference Global environment 6

7 Bindings \$, + etc are just identifiers > (\$ 4 5) reference to an identifier before its definition: \$ > (define \$ +) > (\$ 4 5) 9 > (define sum +) sum > (sum 4 5) 9... * + \$ sum * + environment = set of bindings 7

8 Scheme s Syntax: S-Expressions Symbolic Expression 1. An atom, or 2. An combination of the form (E1. E2) where E1 and E2 are S-expressions. atoms can be numbers, symbols, strings, booleans, (x y z) is used as an abbreviation for (x. (y. (z. ()))) () is pronounced nil or null or the empty list Scheme (define (fac n) (if (= n 1) 1 (* n (fac (- n 1))))) 8 Common Lisp (defun factorial (x) (if (zerop x) 1 (* x (factorial (- x 1)))))

9 Evaluation Rules: Version 1 To evaluate an expression: recursive rule numerals evaluate to numbers identifiers evaluate to the value of their binding combinations: - evaluate all the subexpressions in the combination - apply the procedure that is the value of the leftmost expression (= the operator) to the arguments that are the values of the other expressions (= the operands) some expressions (e.g. define) have a specialized evaluation rule. These are called special forms. 9

10 Procedure Definitions (define (square x) (* x x)) To square something, multiply it by itself. (define (<identifier> <formal parameters>) <body>) 10

11 Procedures (ctd) > (define (square x) (* x x)) > (square 21) 441 > (square (+ 2 5)) 49 > (square (square 81)) > (define (sum-of-squares x y) (+ (square x) (square y))) > (sum-of-squares 3 4) 25 > (define (f a) (sum-of-squares (+ a 1) (* a 2))) > (f 5) 136 > procedure application procedure definition building layers of abstraction 11

12 The Substitution Model of Evaluation A mental model to explain how procedure application works (f 5) (sum-of-squares (+ a 1) (* a 2)) (sum-of-squares (+ 5 1) (* 5 2)) (sum-of-squares 6 10) (+ (square x) (square y)) (+ (square 6) (square 10)) (+ (* x x) (square 10)) (+ (* 6 6) (square 10)) (+ 36 (square 10)) (+ 36 (* x x)) (+ 36 (* 10 10)) ( ) 136 x a 5 x 6, y 10 x 6

13 Applicative vs. Normal Order (f 5) (sum-of-squares (+ 5 1) (* 5 2)) alternative evaluation model (+ (square (+ 5 1)) (square (* 5 2))) (+ (* (+ 5 1) (+ 5 1)) (square (* 5 2))) (+ (* (+ 5 1) (+ 5 1)) (* (* 5 2) (* 5 2))) (+ (* 6 6) (* 10 10)) ( ) Scheme uses applicative order.

14 Boolean Values c.f. truth tables > #t #t > #f #f > (= 1 1) #t > (= 1 2) #f > (define true #t) > true #t > (define false #f) > false #f > (and #t #f) #f predicates > (and (> 5 1) (< 2 5) (= 1 1)) #t > (or (= 0 1) (> 2 1)) #t > (not #t) #f > (not 1) #f everything is #t, except #f > (and 1 2 3) 3 > (or 1 2 3) 1 > (and #f (= "hurray" (/ 1 0))) #f > (or #t (/ 1 0)) #t special forms 14

15 case analysis with cond { x if x>0 x = 0 if x=0 -x if x<0 > (define (abs x) (cond ((> x 0) x) ((= x 0) 0) ((< x 0) (- x)))) > (abs 12) 12 > (abs -3) 3 > (abs 0) 0 (cond (<p1> <e1>) (<p2> <e2>)... (<pn> <en>)) 15

16 Shorthands > (define (abs x) (cond ((< x 0) (- x)) (else x))) > (abs -3) 3 > (abs 3) 3 > (define (abs x) (if (< x 0) (- x) x)) > (abs -3) 3 (if <predicate> <consequent> <alternative>) 16

17 Special Forms cond define if or and so far To evaluate a composite expression of the form (f a1 a2... ak) if f is a special form, use a dedicated evaluation method otherwise, consider f as a procedure application 17

18 Case Study: Square Roots Definition: x = y <=> y >= 0 and y 2 =x Procedure: IF y is guess for x y THEN y + is a better guess x 2 what is how to 18 Newton s approximation method

19 Newton s Iteration Method > (define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) > (define (improve guess x) (average guess (/ x guess))) > (define (average x y) (/ (+ x y) 2)) > (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) > (define (sqrt x) (sqrt-iter 1.0 x)) > (define (square x) (* x x)) > (sqrt 9) Iteration is done by ordinary procedure applications sqrt-iter is a recursive (Eng: re-occur) procedure procedures are black-box abstractions and can be composed procedural abstraction 19

20 Free vs. Bound Identifiers A procedure definition binds the formal parameters. The expression in which the identifier is bound (i.e. the body) is called the scope of the binding. Unbound identifiers are called free. good-enough? guess and x are being bound here > (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) abs < - square are free Bound formal parameters are always local to the procedure. 20 Free identifiers are expected to be bound by the global environment.

21 Polluted Global Environment > (define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) > (define (improve guess x) (average guess (/ x guess))) > (define (average x y) (/ (+ x y) 2)) > (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) > (define (sqrt x) (sqrt-iter 1.0 x)) > (define (square x) (* x x)) > (sqrt 9) Only sqrt is of interest to users The others are auxiliar procedures But everyone can see them 21

22 Solution: Local Definitions (define (sqrt x) (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) (define (improve guess x) (average guess (/ x guess))) (define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) (sqrt-iter 1.0 x)) Procedures can have local definitions aka block structure (define (<identifier> <formal parameters>) <local definitions> <body>) 22 Revisited

23 Lexical Scoping (define (sqrt x) (define (good-enough? guess) (< (abs (- (square guess) x)) 0.001)) (define (improve guess) (average guess (/ x guess))) (define (sqrt-iter guess) (if (good-enough? guess) guess (sqrt-iter (improve guess)))) (sqrt-iter 1.0)) formal parameters can be free identifiers in the nested definitions 23

24 Lexical Scoping vs. Dynamic Scoping Lexical scope: the meaning of a variable depends on the location in the source code and the lexical context. It is defined by the definition of the variable. original Lisp, Perl Dynamic scope: the meaning of a variable depends on the execution context that is active when the variable is encountered. aka dynamic binding this or self in OOP aka static binding most languages aka static scope sub proc1 { print \$var\n"; } sub proc2 { local \$var = 'local'; proc1(); } \$var = 'global'; void mymethod(y) { return this.x + y } 24 proc1(); # print 'global' proc2(); # print 'local'

25 Recursion Recursion (define (fac n) (if (= n 1) 1 (* n (fac (- n 1))))) (fac 5) (* 5 (fac 4)) (* 5 (* 4 (fac 3))) (* 5 (* 4 (* 3 (fac 2)))) (* 5 (* 4 (* 3 (* 2 (fac 1))))) (* 5 (* 4 (* 3 (* 2 1)))) (* 5 (* 4 (* 3 2))) (* 5 (* 4 6)) (* 5 24) 120 linear recursive process 25 accumulator (define (fac n) (fac-iter 1 1 n)) (define (fac-iter product counter max) (if (> counter max) product (fac-iter (* counter product) (+ counter 1) max))) (fac 5) (fac-iter 1 1 5) (fac-iter 1 2 5) (fac-iter 2 3 5) (fac-iter 6 4 5) (fac-iter ) (fac-iter ) 120 linear iterative process

26 Definition There is a difference between a recursive procedure and a recursive process. An iterative process is a computational process that can be executed with a fixed number of state variables. (define (fac n) (fac-iter 1 1 n)) (define (fac-iter product counter max) (if (> counter max) product accumulator (fac-iter (* counter product) (+ counter 1) max))) 3 state variables 26

27 Tail Call Optimisation A recursive procedure that generates an iterative process is also known as a tail-recursive procedure. Recursion is implemented by means of a runtime stack. Tall-recursive procedures do not need a stack. A compiler that can handle this is said to do tail call optimisation. (define (fac n) (fac-iter 1 1 n)) (define (fac-iter product counter max) (if (> counter max) product (fac-iter (* counter product) (+ counter 1) max))) Tail call optimisation is part of the Scheme s language definition 27 var product = 1 var counter = 1 var max = n 3 state variables label fac-iter if (> counter max) return product else product = (* counter product) counter = (+ counter 1) max = max goto fac-iter

28 Tail Call Optimisation (ctd) > (define (happy-printing) (display ":-)") (happy-printing)) Scheme >>> def happy_printing(): print ":-)", happy_printing() Python > :-):-):-):-):-):-):-):-):-):-): -):-):-):-):-):-):-):-):-):-):-): -):-):-):-):-):-):-):-):-):-):-): -):-):-):-):-):-):-):-):-):-):-): -):-):-):-):-):-):-):-):-):-):-): -):-):-):-):-).. user break >>> happy_printing() :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) Python runs out of stack space :-) :-) :-) :-) :-) :-) :-) :-) :-) :-) Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> happy_printing()

29 Tree Recursive Processes fib(5) (define (fib n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2)))))) fib(4) fib(3) fib(3) fib(2) fib(2) fib(1) fib(2) fib(1) fib(1) fib(0) fib(1) fib(0) fib(1) fib(0) tree recursive process accumulators (define (fib-iter a b count) (if (= count 0) b (fib-iter (+ a b) a (- count 1)))) (define (fib n) (fib-iter 1 0 n)) linear iterative process 29

30 (define (exp1 b n) (if (= n 0) 1 (* b (exp1 b (- n 1))))) Exponentiation linear recursive process linear iterative process accumulator (define (exp2 b n) (exp-iter b n 1)) (define (exp-iter b counter product) (if (= counter 0) product (exp-iter b (- counter 1) (* b product)))) logaritmic recursive process (define (exp3 b n) (cond ((= n 0) 1) ((even? n) (square (exp3 b (/ n 2)))) (else (* b (exp3 b (- n 1)))))) 30

31 Higher-Order Procedures A higher-order procedure is a procedure that accepts (a) procedure(s) as argument(s) or one that returns a procedure as the result. Programming languages put restrictions on the ways elements can be manipulated. Elements with the fewest restrictions are said to have first-class status. Some of the rights and privileges of first-class elements are: - they may be bound to variables - they may be passed as arguments to procedures - they may be returned as results of procedures - they may be included in data structures 31 In Scheme, procedures are first-class citizens

32 Abstracting Common Structure (define (sum-integers a b) (if (> a b) 0 (+ a (sum-integers (+ a 1) b)))) (define (sum-cubes a b) (if (> a b) 0 (+ (cube a) (sum-cubes (+ a 1) b)))) (define (cube x) (* x x x)) (define (pi-sum a b) (if (> a b) 0 (+ (/ 1.0 (* a (+ a 2)) (pi-sum (+ a 4) b))))) converges to π

33 Procedures as Argument higher-order procedure (define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b)))) (define (inc n) (+ n 1)) (define (sum-cubes2 a b) (sum cube a inc b)) (define (identity x) x) (define (sum-integers2 a b) (sum identity a inc b)) (define (pi-sum2 a b) (define (pi-term x) (/ 1.0 (* x (+ x 2)))) (define (pi-next x) (+ x 4)) (sum pi-term a pi-next b)) 33

34 Example of Reuse (define (integral f a b dx) (define (add-dx x) (+ x dx)) (* (sum f (+ a (/ dx 2.0)) add-dx b) dx)) > (integral cube )

35 Anonymous Procedures (define (inc n) (+ n 1)) (define (sum-cubes2 a b) (sum cube a inc b)) single usage procedures (define (identity x) x) (define (sum-integers2 a b) (sum identity a inc b)) (lambda (<formal parameters>) <body>) (define (pi-sum2 a b) (define (pi-term x) (/ 1.0 (* x (+ x 2)))) (define (pi-next x) (+ x 4)) (sum pi-term a pi-next b)) (define (pi-next x) (+ x 4)) (lambda (x) (+ x 4)) The procedure of an argument x that adds x to 4 35

36 Insight create a procedure and name it (define (<identifier> <formal parameters>) <body>) (lambda (<formal parameters>) <body>) + (define <identifier> <expression>) create a procedure and name it 36

37 Examples (define (pi-sum2 a b) (define (pi-term x) (/ 1.0 (* x (+ x 2)))) (define (pi-next x) (+ x 4)) (sum pi-term a pi-next b)) (define (pi-sum3 a b) (sum (lambda (x) (/ 1.0 (* x (+ x 2)))) a (lambda (x) (+ x 4)) b)) (define (integral f a b dx) (define (add-dx x) (+ x dx)) (* (sum f (+ a (/ dx 2.0)) add-dx b) dx)) (define (integral f a b dx) (* (sum f (+ a (/ dx 2.0)) (lambda (x) (+ x dx)) b) dx)) 37

38 Local Bindings f(x,y) = x(1+xy) 2 + y(1-y) + (1+xy)(1-y) is less clear than: a = (1+xy) b = (1-y) f(x,y) = xa 2 + yb + ab (define (f x y) (let ((a (+ 1 (* x y))) (b (- 1 y))) (+ (* x (square a)) (* y b) (* a b)))) can be used as locally as possible; in any expression 38 (let ((<var1> <exp1>) (<var2> <exp2>)... (<varn> <expn>)) <body>)

39 Insight (let ((<var1> <exp1>) (<var2> <exp2>)... (<varn> <expn>)) <body>) ((lambda (<var1>... <varn>) <body>) <exp1> <exp2>... <expn>) (let ((x 3) (y (+ x 2))) (* x y)) ((lambda (x y) (* x y)) 3 (+ x 2)) x is free 39 x is free A language construct that is executed by first converting into another (more fundamental) language construct is said to be syntactic sugar.

40 Variation (let* ((<var1> <exp1>) (<var2> <exp2>)... (<varn> <expn>)) <body>) ((lambda (<var1>) ((lambda (<var2>)... ((lambda (<varn>) <body>) <expn>) <exp2>) <exp1>) 40

41 Calculating Fixed-Points x is a fixed-point of f if and only if f(x) = x (define tolerance ) (define (fixed-point f first-guess) (define (close-enough? v1 v2) (< (abs (- v1 v2)) tolerance)) (define (try guess) (let ((next (f guess))) (if (close-enough? guess next) next (try next)))) (try first-guess)) for some f, we can approximate x using some initial guess g and calculate f(g), f(f(g)), f(f(f(g))),... > (fixed-point cos 1.0) > (fixed-point (lambda (y) (+ (sin y) (cos y))) 1.0)

42 Improving Convergence x = y y 0 and y 2 =x y = x/y Hence: (define (sqrt2 x) (fixed-point (lambda (y) (/ x y)) 1.0)) oscillates between 2 values But this does not converge! y1 x/y1 x/ x/y1 = y1 take the average of those values (define (sqrt3 x) (fixed-point (lambda (y) (average y (/ x y))) 1.0)) 42 average damping

43 Making the Essence Explicit I take a procedure I return a procedure (define (average-damp f) (lambda (x) (average x (f x)))) every idea made explicit example > ((average-damp square) 10) 55 (define (sqrt4 x) (fixed-point (average-damp (lambda (y) (/ x y))) 1.0)) 3 x = y y = x/y 2 reuse all ideas (define (cube-root x) (fixed-point (average-damp (lambda (y) (/ x (square y)))) 1.0)) 43 more neat stuff in the book

44 Chapter 1 44

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

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

### Introduction to Functional Programming

Introduction to Functional Programming Xiao Jia xjia@cs.sjtu.edu.cn Summer 2013 Scheme Appeared in 1975 Designed by Guy L. Steele Gerald Jay Sussman Influenced by Lisp, ALGOL Influenced Common Lisp, Haskell,

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

### Modern Programming Languages. Lecture LISP Programming Language An Introduction

Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation

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

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

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

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

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

### Principles of Programming Languages

Ben-Gurion University of the Negev Faculty of Natural Science Department of Computer Science Mira Balaban Lecture Notes April 9, 2013 Many thanks to Tamar Pinhas, Azzam Maraee, Ami Hauptman, Eran Tomer,

### Lambda Calculus LC-1

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

### Recursion & Iteration

Recursion & Iteration York University Department of Computer Science and Engineering 1 Overview Recursion Examples Iteration Examples Iteration vs. Recursion Example [ref.: Chap 5,6 Wilensky] 2 Recursion

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

### LISP. Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits.

LISP Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits. From one perspective, sequences of bits can be interpreted as a code for ordinary decimal digits,

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

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

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

### Vectors in Scheme. Data Structures in Scheme

Data Structures in Scheme Vectors in Scheme In Scheme, lists and S-expressions are basic. Arrays can be simulated using lists, but access to elements deep in the list can be slow (since a list is a linked

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

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

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

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

### 6.001 SICP. Types. Types compound data. Types simple data. Types. Types procedures

Today s topics Types of objects and procedures Procedural abstractions Capturing patterns across procedures Higher Order Procedures Types (+ 5 1) ==> 15 (+ "hi 5) ;The object "hi", passed as the first

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

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

### 61A LECTURE 18 SCHEME. Steven Tang and Eric Tzeng July 24, 2013

61A LECTURE 18 SCHEME Steven Tang and Eric Tzeng July 24, 2013 What s happening today? We re learning a new language! After you know one language (Python), learning your second (Scheme) is much faster

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

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

### (Func&onal (Programming (in (Scheme)))) Jianguo Lu

(Func&onal (Programming (in (Scheme)))) Jianguo Lu 1 Programming paradigms Func&onal No assignment statement No side effect Use recursion Logic OOP AOP 2 What is func&onal programming It is NOT what you

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

### Tail Recursion. ;; a recursive program for factorial (define fact (lambda (m) ;; m is non-negative (if (= m 0) 1 (* m (fact (- m 1))))))

Tail Recursion 1 Tail Recursion In place of loops, in a functional language one employs recursive definitions of functions. It is often easy to write such definitions, given a problem statement. Unfortunately,

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

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

### Functional Programming Languages (FPL)

Functional Programming Languages (FPL) 1. Definitions... 3 2. Applications... 3 3. Examples... 4 4. FPL Characteristics:... 5 5. Lambda calculus (LC)... 6 5.1. LC expressions forms... 6 5.2. Semantic of

### Functions, Conditionals & Predicates

Functions, Conditionals & Predicates York University Department of Computer Science and Engineering 1 Overview Functions as lambda terms Defining functions Variables (bound vs. free, local vs. global)

### Encodings. Using the minimal λ-calculus language we get. functions. local binding. booleans. numbers... and recursive functions?

Part Encodings Using the minimal λ-calculus language we get functions local binding booleans numbers... and recursive functions? Factorial in Plait (local [(define fac (lambda (n) (if (zero? n) (* n (fac

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

### Ruby: Introduction, Basics

Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

### Chapter 15. Functional Programming Languages

Chapter 15 Functional Programming Languages Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming Language: Lisp Introduction

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

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

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

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

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

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

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

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

### COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of

### Ruby: Introduction, Basics

Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

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

### FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE,

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE, 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší budoucnosti L I S P - Introduction L I S P

### Lecture #24: Programming Languages and Programs

Lecture #24: Programming Languages and Programs A programming language is a notation for describing computations or processes. These range from low-level notations, such as machine language or simple hardware

### Building a system for symbolic differentiation

Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)

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

### CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages Functional Programming with Lists CMSC330 Spring 2018 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as

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

### MIDTERM EXAM (Solutions)

MIDTERM EXAM (Solutions) Total Score: 100, Max. Score: 83, Min. Score: 26, Avg. Score: 57.3 1. (10 pts.) List all major categories of programming languages, outline their definitive characteristics and

### Discussion 12 The MCE (solutions)

Discussion 12 The MCE (solutions) ;;;;METACIRCULAR EVALUATOR FROM CHAPTER 4 (SECTIONS 4.1.1-4.1.4) of ;;;; STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS ;;;from section 4.1.4 -- must precede def of

### CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:

### Symbolic Computation and Common Lisp

Symbolic Computation and Common Lisp Dr. Neil T. Dantam CSCI-56, Colorado School of Mines Fall 28 Dantam (Mines CSCI-56) Lisp Fall 28 / 92 Why? Symbolic Computing: Much of this course deals with processing

### Class Structure. Prerequisites

Class Structure Procedural abstraction and recursion 6.037 - Structure and Interpretation of Computer Programs Mike Phillips, Benjamin Barenblat, Leon Shen, Ben Vandiver, Alex Vandiver, Arthur Migdal Massachusetts

### INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS FUNCTION COMPOSITION Instructors: Crista Lopes Copyright Instructors. Topics Recursion Higher-order functions Continuation-Passing Style Monads (take 1) Identity Monad Maybe

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

### CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages Functional Programming with Lists 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as a linked data structure

### Imperative, OO and Functional Languages A C program is

Imperative, OO and Functional Languages A C program is a web of assignment statements, interconnected by control constructs which describe the time sequence in which they are to be executed. In Java programming,

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

### ! The simplest building blocks of a language. ! Compound elements are built from simpler ones

The Elements of Programming Primitive Expressions and Statements! The simplest building blocks of a language 61 Lecture Monday, ugust 9 Means of Combination! Compound elements are built from simpler ones

### Computer Science 21b: Structure and Interpretation of Computer Programs (Spring Term, 2004)

Computer Science 21b: Structure and Interpretation of Computer Programs (Spring Term, 2004) There are only 5 ideas in Computer Science, and by the end of this course, you ll know 3 of them --Harry Mairson

### Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Fall Semester, 1996 Lecture Notes { October 31,

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