CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 7.

Slides:



Advertisements
Similar presentations
Lisp. Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks.
Advertisements

C-LISP. LISP 2 Lisp was invented by John McCarthy in 1958 while he was at the Massachusetts Institute of Technology (MIT).John McCarthyMassachusetts Institute.
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
1 Programming Languages and Paradigms Lisp Programming.
Lambda Calculus and Lisp PZ03J. Lambda Calculus The lambda calculus is a model for functional programming like Turing machines are models for imperative.
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Apply-to-all A functional form that takes a single function as a parameter and yields a list of values obtained.
1-1 An Introduction to Scheme March Introduction A mid-1970s dialect of LISP, designed to be a cleaner, more modern, and simpler version than.
1 Functional programming Languages And a brief introduction to Lisp and Scheme.
Lisp. Versions of LISP Lisp is an old language with many variants –LISP is an acronym for List Processing language Lisp is alive and well today Most modern.
CS 330 Programming Languages 11 / 20 / 2007 Instructor: Michael Eckmann.
Chapter 15 Functional Programming Languages. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Introduction Design of imperative languages is.
Symbolic Expressions (S Expressions) Syntax: Opening and Closing parenthesis having elements in between. List represented in LISP: (A B2 C3 Shahid) (A.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Recursion in Scheme recursion is the basic means for expressing repetition some recursion is on numbers –factorial –fibonacci some recursion is on structures.
1 (Functional (Programming (in (Scheme)))) Jianguo Lu.
Comp. Eng. SW Lab II: FP with Scheme 1 Computer Eng. Software Lab II , Semester 2, Who I am: Andrew Davison CoE, WiG Lab Office.
CS 152: Programming Language Paradigms February 24 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
Slide 1 Vitaly Shmatikov CS 345 Introduction to Scheme.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
CS 330 Programming Languages 11 / 21 / 2006 Instructor: Michael Eckmann.
Scheme & Functional Programming. ( ) >> 64 ( ) >> 666 (* ) >> 1200 (+ (* 3 5) (- 10 6)) >> 19.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
CS 403: Programming Languages Lecture 6 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 8.
CS 330 Programming Languages 11 / 13 / 2008 Instructor: Michael Eckmann.
COP4020 Programming Languages Functional Programming Prof. Xin Yuan.
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
David Evans CS200: Computer Science University of Virginia Computer Science Lecture 19: Environments.
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
CS 330 Programming Languages 11 / 15 / 2007 Instructor: Michael Eckmann.
1 Data Abstraction. Pairs and Lists. (SICP Sections – 2.2.1)
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
Computer Eng. Software Lab II , Semester 2, Who I am: Andrew Davison CoE, WiG Lab Office Functional Programming.
מבוא מורחב שיעור 7 1 Lecture 7 Data Abstraction. Pairs and Lists. (Sections – 2.2.1)
CS 152: Programming Language Paradigms February 12 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
1 Outline Review Introduction to LISP Symbols and Numbers Lists Writing LISP Functions LISPWorks.
CS314 – Section 5 Recitation 9
Functional Programming
CS314 – Section 5 Recitation 10
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation
Section 15.4, 15.6 plus other materials
Lecture 16 Streams continue Infinite Streams מבוא מורחב - שיעור 16.
CS 326 Programming Languages, Concepts and Implementation
Example of formula (defun roots (a b c) (list
PPL Lecture Notes: Chapter 3 High-Order Procedures Revisited.
PPL Lazy Lists.
CS 326 Programming Languages, Concepts and Implementation
CS 326 Programming Languages, Concepts and Implementation
Chapter 15 – Functional Programming Languages
September 4, 1997 Programming Languages (CS 550) Lecture 6 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts.
Closures and Streams cs784(Prasad) L11Clos
COP4020 Programming Languages
Introduction to Functional Programming in Racket
Nondeterministic Evaluation
Using Lisp Lisp is a interactive system
Proving Properties of Recursive List Functions
Lisp Tutorial Click on Xlisp icon – you enter the interpreter
The Metacircular Evaluator (Continued)
Lecture 26: The Metacircular Evaluator Eval Apply
Streams, Delayed Evaluation and a Normal Order Interpreter
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
6.001 SICP Variations on a Scheme
Introduction to Functional Programming in Racket
Announcements Quiz 5 HW6 due October 23
Common Lisp II.
Lisp.
More Scheme CS 331.
Lecture 25: The Metacircular Evaluator Eval Apply
Presentation transcript:

CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 7

22/69 Recursion How do you THINK recursively? Example: define factorial factorial(n) = 1 * 2 * 3 *...(n-1) * n factorial (n-1) 1if n=1 (the base case) factorial(n) = n * factorial(n-1) otherwise(inductive step)

33/69 Recursion Implement factorial in Scheme: (define (factorial n) (if (= n 1) 1 (* n (factorial (- n 1))))) (factorial 4)=> 24

44/69 Recursion Fibonacci: 0if n = 0 fib(n) = 1if n = 1 fib(n-1) + fib(n-2)otherwise Implement in Scheme: (define (fib n) (cond ((= n 0) 0) ((= n 1) 1) (else (+ (fib (- n 1)) (fib (- n 2))))))

55/69 Recursion Length of a list: 0if list is empty len(lst) = 1 + len ( lst-without-first-element )otherwise Implement in Scheme: (define (len lst) (if (null? lst) 0 (+ 1 (len (cdr lst)))))

66/69 Recursion Sum of elements in a list of numbers: 0 if list is empty sum(lst) = first-element + sum (lst-without-first-element) otherwise (define (sum lst) (if (null? lst) 0 (+ (car lst) (sum (cdr lst))))) Implement in Scheme:

77/69 Recursion Check membership in a list: (define (member? x lst) (cond ((null? lst) #f) ((equal? x (car lst)) #t) (else (member? x (cdr lst)))))

88/69 Interacting with Scheme Instead of writing everything at the Scheme prompt, you can: −write your function definitions and your global variable definitions (define...) in a file ("file_name") −at the Scheme prompt, load the file with:(load "file_name") −at the Scheme prompt call the desired functions −there is no "formal" main function You can also invoke Scheme directly from Emacs: −M-x run-scheme −this will open another buffer, showing the Scheme prompt −then you can switch between the buffer where you edit your program and the buffer with the Scheme prompt −BONUS: when closing a parenthesis, Emacs will highlight the corresponding open one

99/69 Recursion Return a reversed list: (define (reverse lst) (if (null? lst) lst (append (reverse (cdr lst)) (list (car lst))))) Return the nth element in a list: (cadddddddd...dddddddr lst) ; don't try this at home! (define (nth lst n); assumes lst is non-empty and n >= 0 (if (= n 0) (car lst) (nth (cdr lst) (- n 1))))

1010/69 Recursion In general: −When recurring on a list lst, ask two questions about it: (null? lst) and else −When recurring on a number n, ask two questions about it: (= n 0) and else −When recurring on a list lst, make your recursive call on (cdr lst) −When recurring on a number n, make your recursive call on (- n 1)

1111/69 Local Definitions let - has a list of bindings and a body - each binding associates a name to a value - bindings are local (visible only in the body of let) - let returns the last expression in the body > (let ((a 2) (b 3)); list of bindings (+ a b)); body - expression to evaluate and return 5 a=> Error: variable a is not bound. b=> Error: variable b is not bound.

1212/69 Local Definitions Factor out common sub-expressions: f(x,y) = x(1+xy) 2 + y(1-y) + (1+xy)(1-y) a = 1+xy b = 1-y f(x,y) = xa 2 + yb + ab

1313/69 Local Definitions a = 1+xy b = 1-y f(x,y) = xa 2 + yb + ab Locally define the common sub-expressions: (define (f x y) (let ((a (+ 1 (* x y))) (b (- 1 y))) (+ (* x a a) (* y b) (* a b)))) (f 1 2)=> 4

1414/69 Local Definitions Functions can also be declared locally: (let ((a 3) (b 4) (square (lambda (x) (* x x))) (plus +)) (sqrt (plus (square a) (square b))))=> 5

1515/69 Local Definitions let makes its bindings in parallel: (define x 'a) (define y 'b) (list x y)=> (a b) (let ((x y) (y x)) (list x y))=> 2. Then bind all names in binding list to those values 1. First evaluate all expressions in the binding list ba (b a)

1616/69 Local Definitions Bad let bindings: (let ((x 1) (y (+ x 1))) (list x y))=> Error: variable x is not bound. What if we want y to be computed in terms of x? −Need to use let*

1717/69 Local Definitions let* - similar to let, except that bindings are made sequentially (let* ((x 1) (y (+ x 1))) (list x y))=> (1 2) How can you do this using let? let* is equivalent to ("syntactic sugar" for): (let ((x 1)) (let ((y (+ x 1))) (list x y)))

1818/69 Local Definitions What if we want to locally define a recursive function? letrec - similar to let*, but allows recursive definitions Define factorial locally: (letrec ((factorial (lambda (n) (if (= n 1) 1 (* n (factorial (- n 1))))))) (factorial 5)) => 120

1919/69 Indentation Indentation is essential in Scheme. With all these parentheses, we need something to depend on There are two main schools of thought on this: (define (f x) (let ((a 1)) (if (< x 5) (+ a x) (* a x)))) (define (f x) (let ((a 1)) (if (< x 5) (+ a x) (* a x) ) OR You may choose the style you like most, but be consistent and ALWAYS indent. Otherwise you will not be able to read or debug your own program

2020/69 Input and Output read - returns the input from the keyboard > (read) 234; user types this 234; the read function returns this > (read) "hello world" display - prints its single parameter to the screen > (display "hello world") hello world > (display (+ 2 3)) 5

2121/69 Input and Output newline - displays a new line Define a function that asks for input: (define (ask-them str) (display str) (read)) > (ask-them "How old are you? ") How old are you? 32 32

2222/69 Input and Output Define a function that asks for a number (if it’s not a number it keeps asking): (define (ask-number) (display "Enter a number: ") (let ((n (read))) (if (number? n) n (ask-number)))) > (ask-number) Enter a number: a Enter a number: (5 6) Enter a number: "Why don't you like these?" Enter a number: 7 7

2323/69 Input and Output An outer-level function to go with factorial, that reads the input, computes the factorial and displays the result: (define (factorial-interactive) (display "Enter an integer: ") (let ((n (read))) (display "The factorial of ") (display n) (display " is ") (display (factorial n)) (newline))) > (factorial-interactive) Enter an integer: 4 The factorial of 4 is 24

2424/69 Higher-Order Functions In Scheme, a function is a first-class object – it can be passed as an argument to another function, it can be returned as a result from another function, and it can be created dynamically A function is called a higher-order function if it takes a function as a parameter, or returns a function as a result

2525/69 Higher-Order Functions map −takes as arguments a function and a sequence of lists −there must be as many lists as arguments of the function, and lists must have same length −applies the function on corresponding sets of elements from the lists −returns all the results in a list (define (square x) (* x x)) (map square '( ))=> ( ) (map + '(1 2 3) '(4 5 6))=> You can also define the function in-place: (map (lambda (x) (* 2 x)) '(1 2 3))=> (5 7 9) (2 4 6)

2626/69 Announcements Readings −May look at Scheme books or on-line references