CSE 341 Lecture 16 More Scheme: lists; helpers; let/let*; higher-order functions; lambdas slides created by Marty Stepp http://www.cs.washington.edu/341/

Slides:



Advertisements
Similar presentations
Higher-order functions in ML
Advertisements

F28PL1 Programming Languages Lecture 14: Standard ML 4.
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
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.
מבוא מורחב - שיעור 91 Lecture 9 Lists continued: Map, Filter, Accumulate, Lists as interfaces.
Functional programming: LISP Originally developed for symbolic computing Main motivation: include recursion (see McCarthy biographical excerpt on web site).
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.
מבוא מורחב - שיעור 81 Lecture 8 Lists and list operations (continue).
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
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.
CSC3315 (Spring 2009)1 CSC 3315 Programming Paradigms Scheme Language Hamid Harroud School of Science and Engineering, Akhawayn University
331 Final Spring Details 6-8 pm next Monday Comprehensive with more emphasis on material since the midterm Study example finals and midterm exams.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
CS 152: Programming Language Paradigms February 17 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
1 Append: process  (append list1 list2) (cons 1 (append ‘(2) list2)) (cons 1 (cons 2 (append ‘() list2))) (cons 1 (cons 2 list2)) (define (append list1.
Practice session #6: 1. Sequence operations 2. Partial evaluation with currying 3. Lazy-lists.
Functional Programming in Scheme and Lisp.
Fall 2008Programming Development Techniques 1 Topic 8 Sequences as Conventional Interfaces Section October 2008.
Functional Programming: Lisp MacLennan Chapter 10.
Forms Writing your own procedures CS 480/680 – Comparative Languages.
CSE 341 Lecture 8 curried functions Ullman 5.5 slides created by Marty Stepp
CS 152: Programming Language Paradigms February 12 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
1 Introduction to Functional Programming in Racket CS 270 Math Foundations of CS Jeremy Johnson.
CSE 341 Lecture 21 delayed evaluation; thunks; streams slides created by Marty Stepp
CS314 – Section 5 Recitation 10
Additional Scheme examples
Functional Programming
CS 550 Programming Languages Jeremy Johnson
PPL Lecture Notes: Chapter 3 High-Order Procedures Revisited.
PPL Lazy Lists.
Introduction to Scheme
CSE 341 Lecture 5 efficiency issues; tail recursion; print
Racket CSC270 Pepper major portions credited to
Chapter 15 – Functional Programming Languages
CSE 341 Lecture 20 Mutation; memoization slides created by Marty Stepp
CS 270 Math Foundations of CS Jeremy Johnson
COP4020 Programming Languages
Env. Model Implementation
Introduction to Functional Programming in Racket
Nondeterministic Evaluation
6.001 SICP Data abstractions
CSE 341 Lecture 3 let expressions; pattern matching Ullman
The Metacircular Evaluator
FP Foundations, Scheme In Text: Chapter 14.
PPL Sequence Interface.
Dynamic Scoping Lazy Evaluation
The Metacircular Evaluator
Lecture #8 מבוא מורחב.
CS 36 – Chapter 11 Functional programming Features Practice
The Metacircular Evaluator (Continued)
Lecture 26: The Metacircular Evaluator Eval Apply
topics mutable data structures
Introduction to Functional Programming in Racket
6.001 SICP Data abstractions
Announcements Quiz 5 HW6 due October 23
Lecture #7 מבוא מורחב.
CSE 341 Lecture 7 anonymous functions; composition of functions Ullman 5.1.3, 5.6 slides created by Marty Stepp
List and list operations (continue).
Today’s topics Abstractions Procedural Data
Functional Programming: Lisp
Lecture # , , , , מבוא מורחב.
To understand recursion, one must first understand recursion.
CSE 341 Lecture 2 lists and tuples; more functions; mutable state
Lecture 25: The Metacircular Evaluator Eval Apply
Presentation transcript:

CSE 341 Lecture 16 More Scheme: lists; helpers; let/let*; higher-order functions; lambdas slides created by Marty Stepp http://www.cs.washington.edu/341/

Lists (list expr2 ... exprN) '(value1 value2 ... valueN) ; all literals Scheme lists are created with the list procedure the empty list is written as null if you forget list, Scheme will "run" your list as a procedure call, with first element as the procedure name > (define L (1 2 3 4)) procedure application: expected procedure, given: 1; arguments were: 2 3 4 > (define L (list 1 2 3 4)) > L (1 2 3 4)

List procedures to access elements (car list) ; 1st element (ML hd) "car" (cdr list) ; all but 1st (ML tl) "could-er" cadr, cddr, ; 2nd element; all but first 2 caddr, cdddr, ... these bizarre names come from IBM 704 computer op-codes others: first, second, third, ..., rest, last Examples: > (define L (list 1 2 3 4 5)) > (car L) 1 > (cdr L) (2 3 4 5)

More list procedures Examples: (cons expr list) ; expr :: list (append list1 list2 ... listN) ; list1 @ list2 (length list) (null? list) ; list = [] ? others: drop, filter, flatten, foldl, foldr, make-list, map, member, partition, remove-duplicates, split-at, take, take-right, values Examples: > (cons 4 '(1 2 3)) (4 1 2 3) > (append '(1 2) '(30 40 50) '(6 7)) (1 2 30 40 50 6 7)

Scheme exercise Define a procedure sum that accepts a list as a parameter and computes the sum of the elements of the list. (sum (list 1 2 3 4 5)) should evaluate to 15 solution: (define (sum lst) (if (null? lst) (+ (car lst) (sum (cdr lst)))))

Scheme exercise Define a procedure range that accepts min/max integers and returns the list (min, min+1, ..., max-1, max). (range 2 7) should return (2 3 4 5 6 7) solution: (define (range x y) (if (> x y) () (cons x (range (+ x 1) y))))

Scheme exercise Define a procedure named x+y^2 that accepts two numbers x and y as parameters and returns (x + y)2. Example: (x+y^2 3 4) returns 49 ; not an ideal solution... (define (x+y^2 x y) (* (+ x y) (+ x y)))

let expressions ; define vars --> use them (let ((name expr) ... (name expr)) expr) Defines a local symbol that can be used in the last expr notice that it is a list of (name expr) pairs to be defined Example: ; better (define (x+y^2 x y) (let ((sum (+ x y))) (* sum sum)))

Scheme exercise Define a procedure named math!! that accepts two numbers x and y as parameters and returns: (x + y)2 * (x + y + 2)2 Example: (math!! 3 2) returns 1225 ; not an ideal solution... (define (math!! x y) (* (* (+ x y) (+ x y)) (* (+ x y 2) (+ x y 2))))

Limitation of let expressions (define (math!! x y) (let ((sum (+ x y)) (sum2 (+ sum 2))) (* sum sum sum2 sum2))) > (math!! 2 3) reference to undefined identifier: sum Problem: A symbol declared within a let list cannot refer to the other symbols defined in that same list!

let* expressions ; define vars --> use them (let* ((name expr) ... (name expr)) expr) same as let, but the symbols are evaluated in sequence, so later ones can refer to earlier ones slower / restricts evaluation order, so not default Example: (define (math!! x y) (let* ((sum (+ x y)) (sum2 (+ sum 2))) (* sum sum sum2 sum2)))

Helper procedures w/ define (outer-name param1 param2 ... paramN) (define (inner-name param1 ... paramN) expr1) expr2) You can define a local helper with a nested define the outer function's expr2 can call the inner procedure the inner procedure is visible only to the outer procedure analogous to let with functions in ML

Helper procedure example ; least common multiple of integers a and b ; lcm(a, b) = (a * b) / gcd(a, b) (define (lcmult a b) (define (gcd x y) (if (= y 0) x (gcd y (remainder x y)))) (/ (* a b) (gcd a b))) (had to name it lcmult because lcm already exists)

Higher-order procedures ; apply procedure f to each element of lst (map f lst) ; retain only elements where p returns #t (filter p lst) ; reduce list; f takes 2 elements -> 1 (foldl f initialValue lst) (foldr f initialValue lst) equivalent to ML's map/List.filter/fold* each takes a procedure (or "predicate") to apply to a list

Higher-order exercise Implement our own versions of map and filter, named mapx and filterx. e.g. (mapx f '(1 2 3 4 5)) e.g. (filterx p '(1 2 3 4 5))

Higher-order solutions ; Applies procedure f to every element of lst. (define (mapx f lst) (if (null? lst) () (cons (f (car lst)) (mapx f (cdr lst))))) ; Uses predicate p to keep/exclude elements of lst. (define (filterx p lst) (cond ((null? lst) ()) ((p (car lst)) (cons (car lst) (filterx p (cdr lst)))) (else (filterx p (cdr lst)))))

Anonymous procedures ("lambdas") (lambda (param1 ... paramN) expr) defines an anonymous local procedure you can pass a lambda to a higher-order function, etc. analogous to ML's: fn(params) => expr Example (retain only the even elements of a list): (filter (lambda (n) (= 0 (modulo n 2))) (range 0 100))

Lambda exercise Using higher-order procedures and lambdas, find the sum of the factors of 24. Hint: First get all the factors in a list, then add them. Solution: (foldl + 0 (filter (lambda (n) (= 0 (modulo 24 n))) (range 1 24)))