More Scheme CS 331.

Slides:



Advertisements
Similar presentations
1 Scheme and Functional Programming Aaron Bloomfield CS 415 Fall 2005.
Advertisements

Lists in Lisp and Scheme a. Lists are Lisp’s fundamental data structures, but there are others – Arrays, characters, strings, etc. – Common Lisp has moved.
CSE 3341/655; Part 4 55 A functional program: Collection of functions A function just computes and returns a value No side-effects In fact: No program.
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.
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.
Metacircular Evaluation SICP Chapter 4 Mark Boady.
Scheme for Python Programmers CSE Valeria Montero.
Functional programming: LISP Originally developed for symbolic computing Main motivation: include recursion (see McCarthy biographical excerpt on web site).
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.
Programming Languages I LISP
(5.1) COEN Functional Languages  Functional programming basics  Atoms and lists; cons  Useful primitive functions  Predicates  Arithmetic functions.
1 (Functional (Programming (in (Scheme)))) Jianguo Lu.
Conditionals and Recursion "To iterate is human, to recurse divine." - L. Peter Deutsch.
Functional Programing Referencing material from Programming Language Pragmatics – Third Edition – by Michael L. Scott Andy Balaam (Youtube.com/user/ajbalaam)
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
CSC3315 (Spring 2009)1 CSC 3315 Programming Paradigms Scheme Language Hamid Harroud School of Science and Engineering, Akhawayn University
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 7.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
CS535 Programming Languages Chapter - 10 Functional Programming With Lists.
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
1 Vectors, binary search, and sorting. 2 We know about lists O(n) time to get the n-th item. Consecutive cons cell are not necessarily consecutive in.
CS314 – Section 5 Recitation 9
Operational Semantics of Scheme
Functional Programming
CS314 – Section 5 Recitation 10
Section 15.4, 15.6 plus other materials
Tail Recursion.
Edited by Original material by Eric Grimson
CS 550 Programming Languages Jeremy Johnson
CS 326 Programming Languages, Concepts and Implementation
Pairs and Lists. Data Abstraction. SICP: Sections – 2.2.1
Introduction to Scheme
Variables, Environments and Closures
CSC 533: Programming Languages Spring 2017
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.
Lists in Lisp and Scheme
CSC 533: Programming Languages Spring 2016
COP4020 Programming Languages
Env. Model Implementation
Nondeterministic Evaluation
The Metacircular Evaluator
FP Foundations, Scheme In Text: Chapter 14.
Dynamic Scoping Lazy Evaluation
The Metacircular Evaluator
The Metacircular Evaluator (Continued)
CSE S. Tanimoto Explicit Function Application
Explicit Application of Procedures, and Explicit Evaluation
Lecture 12: Message passing The Environment Model
Data Mutation Primitive and compound data mutators set! for names
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
6.001 SICP Variations on a Scheme
Mutators for compound data Stack Queue
6.001 SICP Data Mutation Primitive and Compound Data Mutators
Announcements Quiz 5 HW6 due October 23
6.001 SICP Interpretation Parts of an interpreter
Lisp: Using Functions as Data
COP4020 Programming Languages
topics interpreters meta-linguistic abstraction eval and apply
Common Lisp II.
Lisp.
Defining Macros in Scheme
Presentation transcript:

More Scheme CS 331

Quiz What is (car ‘((2) 3 4))? What is (cdr ‘((2) (3) (4)))? ((3)(4)) What is (cons ‘2 ‘(2 3 4))? (2 2 3 4) What is the length of the list ‘(()()()())? 4 Which element does (car (cdr ‘(x y z))) extract from the list? y What do some people thing LISP stands for? Losta Insane Stupid Parenthesis

Reading Input (read) returns whatever is input at the keyboard (define x (read)) 55 x

Display Output Use display: (display (+ 3 4)) (display x) (newline) ; output newline Can use to add to functions for debugging or use Trace functions

Trace – Shows function calls Choose “PLT/Textual (MzScheme, includes R5RS)” as your language Add (require (lib "trace.ss")) to the top of your program Add (trace functionname) or (untrace functionname) to turn off tracing

Structure of Lists List : a sequence of zero of more elements May be heterogeneous (a 20 (20 20) (lambda (x) (+ x x))) List of Lists (+ 3 4) A list An expression Allows expression to be built and then evaluated

Tree structure of lists (a b c) (cons a (cons b (cons c ‘()) ) a b c ( )

List structure (a (b) (c (d))) a b ( ) ( ) c d ( )

List storage Independent of allocation schemes Familiarity is helpful for assessment Cons is the constructor Allocates a single cell tail head

List structure (a (b) (c (d))) ( ) a b ( ) c ( ) d

Notion of Equality Eq? Equal? Eq?  equal? for symbols. Checks if the two pointers are the same Equal? Checks if the two arguments are lists with “equal” elements. Recursive Structurally the same Eq?  equal? for symbols.

Examples (equal? ‘foo ‘foo)  (eq? ‘foo ‘foo)  true (equal? ‘(a b) ‘(a b)) (eq? ‘(a b) ‘(a b))  false (define x ‘(a b c)) (define y (cons (car x) (cdr x))) (equal? x y) (eq? x y) false

More List Functions append takes two arguments and returns the concatenation of two lists. be careful here not to confuse append with cons. (append '(a b c)  '(d e f))   (a b c d e f) (append '(a b (c))  '((d) e f))   (a b (c) (d) e f) list returns a list constructed from its arguments.  (list 'a)  (a) (list 'a 'b 'c 'd 'e 'f)  (a b c d e f) (list '(a b c))  ((a b c)) (list '(a b c) '(d e f) '(g h i))  ((a b c)(d e f)(g h i))

More List Functions length returns the length of a list. (length '(a b c d ef gh i jk))  8 (length '(a b c d (ef gh i jk)))  5 reverse returns the same list, only in reversed order. Note, this is only shallow reverse. (reverse '(a b d g o))  (o g d b a) (reverse '(a (b d) g o))   (o g (b d) a)

Exercise Write a helper function to return the first half of a list. Here is the main function: Write a helper function to return the second half of a list. Here is the main function: (define (firsthalf lst) (getfirsthalf lst (quotient (length lst) 2)) ) (define (secondhalf lst) (getsecondhalf lst (quotient (length lst) 2)) )

Merge Method Write a method called Merge that merges two sorted lists: (define (Merge x y) )

MergeSort Write a MergeSort method that uses your Merge method to sort a list of numbers. (define (firsthalf lst) (getfirsthalf lst (quotient (length lst) 2)) ) (define (getfirsthalf lst num) (cond ((equal? num 0) '()) (else (cons (car lst) (getfirsthalf (cdr lst) (- num 1))) (define (secondhalf lst) (getsecondhalf lst (quotient (length lst) 2)) (define (getsecondhalf lst num) ((equal? num 0) lst) (getsecondhalf (cdr lst) (- num 1)) (define (merge l1 l2) ((and (null? l1) (null? l2)) '()) ((null? l1) l2) ((null? l2) l1) ((< (car l1) (car l2)) (cons (car l1) (merge (cdr l1) l2))) (else (cons (car l2) (merge l1 (cdr l2)))) )) (define (mergesort lst) ((null? lst) lst) ((equal? (length lst) 1) lst) (merge (mergesort (firsthalf lst)) (mergesort (secondhalf lst))

let & let* (let ((x1 E1) Expressions E1, E2, … En are evaluated …. (xn En)) F) Expressions E1, E2, … En are evaluated Evaluate F with xi’s bound to Ei’s Value of let is the value of F

Local Variables (let & let*) Used to factor out common expressions Introduce names in subexpressions Order of evaluation of expression is undetermined (let) Order of evaluation of expression is sequential (let*)

Examples (let ((x 2) (y x)) y) (let* ((x 2) (y x)) y) 2

Tail recursion A recursive function is tail-recursive if (a) it returns a value without needing recursion OR (b) simply the result of a recursive activation i.e. just return the value at the end Can be efficiently implemented Don’t need stacks Can convert many functions to be tail recursive

Examples Factorial Function (define factorial (lambda(n) (cond ((= n 1) 1) (else (* n (factorial (- n 1)))))))

Examples Factorial Function: Tail Recursive (define factorial2 (lambda(n m) (cond ((= n 1) m) (else (factorial2 (- n 1) (* m n)))))) (define factorial (lambda(n) (factorial2 n 1)))

Examples Getridof Function (get rid of an item from a list) (define getridof (lambda(list item) (cond ((null? list) '()) ((eq? item (car list)) (getridof (cdr list) item)) (else (cons (car list) (getridof (cdr list) item))))))

Examples getridof Function (Tail recursive) (define gro (lambda(list item list2) (cond ((null? list) list2) ((eq? item (car list)) (gro (cdr list) item list2)) (else (gro (cdr list) item (cons (car list) list2)))))) (gro '(x y x z x w) 'x '()) (w z y) In reverse order! Could you put in original order?

Functions Functions are first class citizens in Scheme Variables may be bound to functions Can be passed as parameters Can be returned as values of functions

Functions as First Class Citizens A function may be bound to a variable, we are already doing this: (define add1 (lambda(x) (+ 1 x))) (add1 4) 5

Functions as First Class Citizens Functions can be passed as parameters (define (foo x y) (x y) ) (foo (lambda(x) (+ 1 x)) 4) 5

Functions as First Class Citizens Functions can be returned as values of functions (define (foo x) (lambda(y) (+ x y))) (foo 4) #<closure> ((foo 4) 5) 9

Examples (map) (map cdr ‘((1 2) (3 4)) ((2) (4)) (map car '((a b) (c d) (e f) (g h))) (a c e g) Takes two arguments Function and a list Applies function to the list

Examples (map) (let ((proc (lambda(ls) (cons 'a ls)))) (map proc '((b c) (d e) (f g h)))) ((a b c) (a d e) (a f g h))

Apply (apply + ‘(4 11)) 15 (apply max ‘(3 4 5)) 5 (apply <function> <arguments-in-a-list>) Useful when the arguments are built separately from application

Eval Eval will evaluate the parameter as a valid Scheme expression (eval ‘(car ‘(a b c)) a (eval ‘(define (foo a b) (+ a b))) foo (foo 3 4) 7 Allows for interesting opportunities for code to modify itself and execute self-generated code

Binding of Variables Global binding Local binding define Local binding lambda, let, letrec How do we change the value of a variable to which it is bound? We have been using define multiple times, although in some implementations of Scheme this is invalid

set! (set! var val) Evaluate val and bind it to var ! Indicates a side effect Scheme does not specify what this returns Implementation dependent DrScheme seems to return nothing

Examples (define f (lambda(x) (+ x 10))) (f 5) >15 (set! f (lambda(x) (* x 10))) >50

Examples (let ((f (lambda(x) (+ x 100)))) (display (f 5)) (newline) (set! f (lambda(x) (* x 100))) (f 5)) 105 500 (f 5) Error, reference to undefined identifier: f Scheme uses lexical scoping.

set-car! & set-cdr! (define x '(4 5 6)) (set-car! x 7) x > (7 5 6) (set-cdr! x '( 7 8 9)) >(7 7 8 9)

More Examples (define (my-reverse ls) (cond ((null? ls) '()) (else (append (my-reverse (cdr ls)) (list (car ls)))))) (my-reverse '(a b c d))

Recursive Functions (define (super-reverse ls) (cond ((null? ls) '()) ((atom? ls) ls) (else (append (super-reverse (cdr ls)) (list (super-reverse (car ls))))))) (super-reverse '((a b) ((c d) e) f))

Recursive Functions (define (pairup x y) (cond ((null? x) '()) ((null? y) '()) (else (cons (list (car x) (car y)) (pairup (cdr x) (cdr y)))))) (pairup '(a b c) '(1 2 3))

Recursive Functions (define (listify ls) (cond ((null? ls) '()) (else (cons (list (car ls)) (listify (cdr ls)))))) (listify '(1 2 2 3))

Summary Pure functional programming No assignments (side effects) Refreshingly simple Surprisingly powerful Recursion Functions as first class objects Implicit storage management Garbage Collection