PPL Sequence Interface.

Slides:



Advertisements
Similar presentations
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 5. 2 List Utilities Scheme built-in procedures –(list x y z...) –(list-ref lst index) –(length lst) –(append.
Advertisements

Programming with Lists
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.
CSE 341 Lecture 16 More Scheme: lists; helpers; let/let*; higher-order functions; lambdas slides created by Marty Stepp
מבוא מורחב - שיעור 91 Lecture 9 Lists continued: Map, Filter, Accumulate, Lists as interfaces.
Cs7100(Prasad)L11Clos1 Closures and Streams. Contemporary Interest in Closures The concept of closures was developed in the 1960s and was first fully.
6.001 SICP SICP – October Trees Trevor Darrell 32-D512 Office Hour: W web page:
6.001 SICP SICP – October HOPs, Lists, Trees Trevor Darrell 32-D512 Office Hour: W web page:
מבוא מורחב - שיעור 81 Lecture 8 Lists and list operations (continue).
( (lambda (z) (define x (lambda (x) (lambda (y z) (y x)))) ( ( (x (lambda () z)) (lambda (z) z) 3 ) ) ) 2)
מבוא מורחב 1 Lecture #8. מבוא מורחב 2 Shall we have some real fun.. Lets write a procedure scramble.. (scramble (list )) ==> ( ) (scramble.
PPL Pairs, lists and data abstraction. Data Abstraction? An interface: separate implementation from usage Think of the Map interface in Java: we know.
PPL Pairs, lists and data abstraction. Compound Data Until now: atomic, unrelated entities Now: organized into structures Why? – Better conceptual level.
CS 152: Programming Language Paradigms February 24 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
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,
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.
Today’s topic: Abstraction Compound Data Data Abstractions: Isolate use of data abstraction from details of implementation Relationship between data abstraction.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 8.
Functional Programming in Scheme and Lisp.
Abstraction: Procedures as Parameters CMSC Introduction to Computer Programming October 14, 2002.
PPL Lazy Lists. Midterm 2012 (define sum-vals (λ (ts) (if (ts-simple? ts) (ts-val ts) (accumulate + 0 (map ts-val (ts-inner-slots ts))))))
Fall 2008Programming Development Techniques 1 Topic 8 Sequences as Conventional Interfaces Section October 2008.
PPL CPS. Moed A 2007 Solution (define scale-tree (λ (tree factor) (map (λ (sub-tree) (if (list? sub-tree) (scale-tree sub-tree factor) (* sub-tree.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 8. Outline 1.The special form quote 2.Data abstraction: Trie 3.Alternative list: Triplets 4.Accumulate-n.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 6. 2 List Utilities Scheme built-in procedures –(list x y z...) –(list-ref lst index) –(length lst) –(append.
PPL CPS. Moed A 2007 Solution (define scale-tree (λ (tree factor) (map (λ (sub-tree) (if (list? sub-tree) (scale-tree sub-tree factor) (* sub-tree.
Principles Of Programming Languages Lecture 2 Today Design-By-Contract Data Structures: Lists and Pairs Iteration vs. Recursion If we have time: live.
CS314 – Section 5 Recitation 9
CS314 – Section 5 Recitation 10
Additional Scheme examples
Chapter 11 - Functional Programming, Part I: Concepts and Scheme
Lecture 16 Streams continue Infinite Streams מבוא מורחב - שיעור 16.
CS 326 Programming Languages, Concepts and Implementation
Pairs and Lists. Data Abstraction. SICP: Sections – 2.2.1
PPL Lecture Notes: Chapter 3 High-Order Procedures Revisited.
PPL Lazy Lists.
(defmacro (delay x) (list 'lambda () x))
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
Env. Model Implementation
Nondeterministic Evaluation
6.001 SICP Data abstractions
Streams Sections 3.5.1,3.5.2 Pages
Lecture 18 Infinite Streams and
FP Foundations, Scheme In Text: Chapter 14.
Lecture 18.
Lecture #8 מבוא מורחב.
CS 36 – Chapter 11 Functional programming Features Practice
6.001 SICP Streams – the lazy way
Chapter 4 Data and Behavior Abstraction
The Metacircular Evaluator (Continued)
Streams, Delayed Evaluation and a Normal Order Interpreter
Streams and Lazy Evaluation in Lisp and Scheme
Lecture 12: Message passing The Environment Model
6.001 SICP Data abstractions
Announcements Quiz 5 HW6 due October 23
Lecture #7 מבוא מורחב.
List and list operations (continue).
Today’s topics Abstractions Procedural Data
Closures and Streams cs7100(Prasad) L11Clos
Lecture # , , , , מבוא מורחב.
More Scheme CS 331.
Lecture 8: Recursing Lists CS150: Computer Science
Presentation transcript:

PPL Sequence Interface

Midterm 2011

(define make-tree (λ (value children) (λ (sel) (sel value children)))) (define root-value (λ (tree) (tree (λ (value children) (value))))) (define tree-children (children)))))

The Sequence Interface Consider the following Java code: int[] mySequence = new int[] {1,2,3,4}; for (int i=0; i<mySequence.length; i++) { System.out.println(mySequence[i]); } Iterating over this sequence is coupled with its implementation.

The Sequence Interface A little better: List<Integer> mySequence = new LinkedList<> {1,2,3,4}; foreach (int j : mySequence) { System.out.println(j); } But still not perfect.

The Sequence Interface OOP languages support collections FP is better: sequence operations Java 8 new feature is sequence operations… Scheme had it for years!

What is Sequence Interface? ADT for lists In other words: a barrier between clients running sequence applications and their implementations Abstracts-away element by element manipulation

Map Applies a procedure to all elements of a list. Returns a list as a result ;Signature: map(proc,sequence) ;Purpose: Apply ’proc’ to all ’sequence’. ;Type: [[T1 -> T2]*LIST(T1) -> LIST(T2)] ;Examples: ;(map abs (list -10 2.5 -11.6 17)) ; ==> (10 2.5 11.6 17) ;(map (lambda (x) (* x x)) (list 1 2 3 4)) ; ==> (1 4 9 16) ;Post-condition: For all i=1..length(sequence): resulti = proc(sequencei)

Map in Java? A little better: mySequence.map((lambda (i) (sysout i))) List<Integer> mySequence = new LinkedList<> {1,2,3,4}; mySequence.map((lambda (i) (sysout i))) Perfect!

Map Example: scale-list Scaling list of numbers by a factor ;Signature: scale-list(items,factor) ;Purpose: Scaling elements of a number list by a factor. ;Type: [LIST(Number)*Number -> LIST(Number)] > (scale-list (list 1 2 3 4 5) 10) (10 20 30 40 50)

Implementation of scale-list No Map Map (define scale-list (lambda (items factor) (if (null? items) (list) (cons (* (car items) factor) (scale-list (cdr items) factor))))) (define scale-list (lambda (items factor) (map (lambda (x) (* x factor)) items))

Map Example: scale-tree Mapping over hierarchical lists >(scale-tree (list 1 (list 2 (list 3 4) 5) (list 6 7)) 10) (10 (20 (30 40) 50) (60 70))

Implementation of scale-tree No Map Map (define scale-tree (lambda (tree factor) (cond ((null? tree) (list)) ((not (list? tree)) (* tree factor)) (else (cons (scale-tree (car tree) factor) (cdr tree) factor)))))) (define scale-tree (lambda (tree factor) (map (lambda (sub-tree) (if (list? sub-tree) (scale-tree sub-tree factor) (* factor))) tree)))

Map in Java List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7); //Old way: for(Integer n: list) { System.out.println(n); } //New way: list.forEach(n -> System.out.println(n)); //Scheme (map list (lambda(n) (display n))

Implementation of Map ;Signature: map(proc,items) ;Purpose: Apply ’proc’ to all ’items’. ;Type: [[T1 -> T2]*LIST(T1) -> LIST(T2)] (define map (lambda (proc items) (if (null? items) (list) (cons (proc (car items)) (map proc (cdr items))))))

A More General Map So far, the procedure can get only a single parameter: an item in the list Map in Scheme is more general: n-ary procedure and n lists (with same length) Example: > (map + (list 1 2 3) (list 40 50 60) (list 700 800 900)) (741 852 963)

Haskell Curry

Function Currying: Reminder Technique for turning a function with n parameters to n functions with a single parameter Good for partial evaluation

Currying ;Type: [Number*Number -> Number] (define add (λ (x y) (+ x y))) ;Type: [Number -> [Number -> Number]] (define c-add (λ (x) (λ (y) (add x y)))) (define add3 (c-add 3)) (add3 4) 7

Why Currying? (define add-fib (lambda (x y) (+ (fib x) y))) (define c-add-fib (lambda (x) (lambda (y) (+ (fib x) y)))) (let ((fib-x (fib x))) (+ fib-x y)))))

Curried Map Delayed List Naïve Version: ;Signature: c-map-proc(proc) ;Purpose: Create a delayed map for ’proc’. ;Type: [[T1 -> T2] -> [LIST(T1) -> LIST(T2)]] (define c-map-proc (lambda (proc) (lambda (lst) (if (empty? lst) lst (cons (proc (car lst)) ((c-map-proc proc) (cdr lst)))))))

Curried Map – delay the list (define c-map-proc (lambda (proc) (letrec ((iter (lambda (lst) (if (empty? lst) lst (cons (proc (car lst)) (iter (cdr lst))))))) iter)))

Curried Map – delay the proc ;; Signature: c-map-list(lst) ;; Purpose: Create a delayed map for ’lst’. ;; Type: [LIST(T1) -> [[T1 -> T2] -> LIST(T2)]] (define c-map-list (lambda (lst) (if (empty? lst) (lambda (proc) lst) ; c-map-list returns a procedure (let ((mapped-cdr (c-map-list (cdr lst)))) ;Inductive Currying (lambda (proc) (cons (proc (car lst)) (mapped-cdr proc)))))))

Filter Homogenous List Signature: filter(predicate, sequence) Purpose: return a list of all sequence elements that satisfy the predicate Type: [[T-> Boolean]*LIST(T) -> LIST(T)] Example: (filter odd? (list 1 2 3 4 5)) ==> (1 3 5) Post-condition: result = sequence - {el|el∈sequence and not(predicate(el))}``

Accumulate Procedure Application Signature: accumulate(op,initial,sequence) Purpose: Accumulate by ’op’ all sequence elements, starting (ending) with ’initial’ Type: [[T1*T2 -> T2]*T2*LIST(T1) -> T2] Examples: (accumulate + 0 (list 1 2 3 4 5)) ==> 15 (accumulate * 1 (list 1 2 3 4 5)) ==> 120

Interval Enumeration Signature: enumerate-interval(low, high) Purpose: List all integers within an interval: Type: [Number*Number -> LIST(Number)] Example: (enumerate-interval 2 7) ==> (2 3 4 5 6 7) Pre-condition: high > low Post-condition: result = (low low+1 ... high)

Enumerate Tree Signature: enumerate-tree(tree) Purpose: List all leaves of a number tree Type: [LIST union T -> LIST(Number)] Example: (enumerate-tree (list 1 (list 2 (list 3 4)) 5)) ==> (1 2 3 4 5) Post-condition: result = flatten(tree)

Sum-odd-squares ; Signature: sum-odd-squares(tree) ; Purpose: return the sum of all odd square leaves ; Type: [LIST -> Number] (define sum-odd-squares (lambda (tree) (accumulate + 0 (map square (filter odd? (enumerate-tree tree))))))

Even Fibonacci Numbers Without sequence operations: With sequence operations: (define even-fibs (lambda (n) (letrec ((next (lambda(k) (if (> k n) (list) (let ((f (fib k))) (if (even? f) (cons f (next (+ k 1))) (next (+ k 1)))))))) (next 0)))) (define even-fibs (lambda (n) (accumulate cons (list) (filter even? (map fib (enumerate-interval 0 n))))))

Filter implementation ;; Signature: filter(predicate, sequence) ;; Purpose: return a list of all sequence elements that satisfy the predicate ;; Type: [[T-> Boolean]*LIST(T) -> LIST(T)] (define filter (lambda (predicate sequence) (cond ((null? sequence) sequence) ((predicate (car sequence)) (cons (car sequence) (filter predicate (cdr sequence)))) (else (filter predicate (cdr sequence))))))

Accumulate Implementation ;; Signature: accumulate(op,initial,sequence) ;; Purpose: Accumulate by ’op’ all sequence elements, starting (ending) ;; with ’initial’ ;; Type: [[T1*T2 -> T2]*T2*LIST(T1) -> T2] (define accumulate (lambda (op initial sequence) (if (null? sequence) initial (op (car sequence) (accumulate op initial (cdr sequence))))))

Enumerate-interval Implementation ;; Signature: enumerate-interval(low, high) ;; Purpose: List all integers within an interval: ;; Type: [Number*Number -> LIST(Number)] (define enumerate-interval (lambda (low high) (if (> low high) (list) (cons low (enumerate-interval (+ low 1) high)))))

Enumerate-Tree Implementation ;; Signature: enumerate-tree(tree) ;; Purpose: List all leaves of a number tree ;; Type: [LIST union T -> LIST(Number)] (define enumerate-tree (lambda (tree) (cond ((null? tree) (tree)) ((not (list? tree)) (list tree)) (else (append (enumerate-tree (car tree)) (enumerate-tree (cdr tree)))))))