Sunteți pe pagina 1din 43

Higher-Order Functions

cs480 (Prasad)

L156HOF

Equivalent Notations
(define (f x y) (body)) = (define f (lambda (x y) (body) ) )
cs480 (Prasad) L156HOF 2

Function Values
(define tag (lambda (t l) (cons t l)) ) (tag int (1)) -> (int 1)

What characterizes a function? Expression in the body of the definition. The sequence of formal parameters.
cs480 (Prasad) L156HOF 3

Anonymous Functions
( (lambda (t int l) (cons t l)) (1) )

Name of the function is irrelevant . Simplification: (define tag cons) Assigning function values is similar to assigning primitive values. (first-class values).
cs480 (Prasad) L156HOF 4

Higher-order Functions
In Scheme, function values can be a) passed to other functions. b) returned from functions. c) stored in data structures. FORTRAN, Ada, etc prohibit a), b), c). Pascal allows only a). LISP/C++/Java support approximations in a round about way. LISP : Meta-programming, C++: Function pointers. Java : via Objects (Closures coming in JDK 7) Scala, Python and C# (delegates) are multi-paradigm languages with support for higher-order functions. ML/Scheme are functional languages that treat function values as first-class citizens.

Implementing subprograms using a stack breaks down here. Heap and garbage collection required.
cs480 (Prasad) L156HOF 5

Applications Abstracting commonly occurring patterns of control. (factoring) Defining generic functions. Instantiating generics. (ORTHOGONALITY)
Eventually contribute to readability, reliability, and reuse. Library: collection of higher-order functions.
cs480 (Prasad) L156HOF 6

Factoring Commonality
(1 2 n) -> (1 4 n^2)
(define (sql L) (if (null? L) () (cons (* (car L) (car L) ) (sql (cdr L)) )))
cs480 (Prasad)

(a b c) -> ((a) (b) (c))


(define (brac L) (if (null? L) () (cons (list (car L) ) (brac (cdr L)) )))
7

L156HOF

The map function


(define (map fn lis) (if (null? lis) () (cons (fn (car lis)) (map fn (cdr lis)) ) ) )
(map (lambda(x) (* x x)) '(1 2 3)) (map (lambda(x) (list x)) '(a b c))

Built-in map:
(map + '(1 2 3) '(4 5 6))
cs480 (Prasad) L156HOF

= (5 7 9)
8

foldr (reduce) and foldl (accumulate)


(Racket : > Intermediate Level) (foldl * 100 (list 2 4 8))

(foldr + 100 (list 2 4 8))

= =

2 + 4 + 8 + 100 114

= =

8 * 4 * 2 * 100 6400

(foldr cons '(c) '(a b))

(foldl cons ' (c) '(a b))

(a b c)

=
L156HOF

(b a c)
9

cs480 (Prasad)

Templates/Generics
(define (imax x y) (if (< x y) y x) ) (define (cmax x y) (if (char-<? x y) y x ) )

Generalization
(define (max lt? x y) (if (lt? x y) y x) )

Specialization
(max string-<? a ab )

Parameterize wrt comparison


cs480 (Prasad)

Passing function values


L156HOF 10

Instantiation
(define (maxg lt?) (lambda (x y) (max lt? ) ( (maxg >) 4 5 ) x y) )

(* customization at run-time *) Function generating function.


Closure construction.

Higher-order functions in a library may be tailored this way for different use.
cs480 (Prasad) L156HOF 11

Recursion vs Higher-Order Functions


(define-struct cost ($)) ; generates code for make-cost & cost-$ (define costList (list (make-cost 5) (make-cost 10) (make-cost 25))) (check-expect (totalCost costList) 40) (check-expect (totalCost costList) (totalCostHF costList))
cs480 (Prasad) L156HOF 12

Simple Recursion vs Map-Reduce version


(define (totalCost cl) (if (null? cl) 0 [+ (cost-$ (car cl)) (totalCost (cdr cl))] ) ) (define (totalCostHF cl) (foldr + 0 (map cost-$ cl))) Both foldl and foldr admissible. Requires DrRacket : > HtDP Intermediate Level
cs480 (Prasad) L156HOF 13

Scoping
Rules governing the association of use of a variable with the corresponding declaration.
proc p (x: int) ; proc q; var y: int; begin x := y begin q end;

end;

Imperative Language : Local / non-local variables. Functional Language : Bound / free variables.
cs480 (Prasad) L156HOF 14

Scoping rules enable determination of declaration corresponding to a non-local / free variable. Alternatives
Fixed at function definition time
Static / lexical scoping
Scheme, Ada, C++, Java, C#, etc

Fixed at function call time


Dynamic scoping
Franz LISP, APL, etc.

cs480 (Prasad)

L156HOF

15

Pascal Example
proc p; var z:int; proc begin proc r; var z:int; begin q end; proc s; var z:int; begin q end; begin end;
cs480 (Prasad) L156HOF 16

q; z := 5 end;

Scoping : z??
Static r: z := 5; s: z := 5; Calls to q in r and s update the variable z declared in p. Dynamic r: z := 5; s: z := 5; Calls to q in r and s update the variables z and z declared in r and s respectively.
L156HOF 17

cs480 (Prasad)

Scoping : functional style


(define y 5) ( (lambda (x) (+ x y)) Point of definition = Point of call. (define (f x) (+ x y)) (define (g y) (f y)) (g 16) Naming context of definition =/= Naming context of call.
cs480 (Prasad) L156HOF 18

3 )

Scoping Rules
Static Scoping (g y) y <- 16 (f y) y <- 16 (+ x y) x <- 16 y <- 5 21 32
cs480 (Prasad) L156HOF 19

Dynamic Scoping (g y) y <- 16 (f y) y <- 16 (+ x y) x <- 16 y <- 16 y <- 5

Closure
(define (addn n) (lambda (x) ) (addn 5)
=

(+ x n) )

(lambda (x) (+x n) )

n <- 5

Closure =

Function Definition + Creation-time environment ( to enforce lexical scoping for free variables )
L156HOF 20

cs480 (Prasad)

Application
Instantiating generic functions. Object-oriented Programming Using (1) let-construct (to introduce local variables) and (2) assignments, objects and classes can be simulated. Streams Creation of infinite data structures.
cs480 (Prasad) L156HOF 21

Lambda Expressions (define (id x) x) (define id (lambda (x) x) ) (lambda (x) x) ( (lambda (x) x) 5 )

(lambda () 5)
cs480 (Prasad) L156HOF 22

Lambda Expressions (lambda () 1) ( (lambda () 1) ) ( (lambda (x) x) (lambda (y) y)

( (lambda (x) (x x)) (lambda (y) y) )


cs480 (Prasad) L156HOF 23

Java : Design Goals


A general-purpose concurrent object-oriented language for the Internet Framework-Oriented Programming
cs480(Prasad) L4javaGoals 24

Familiar
C/C++ syntax

Robust Interpreted
Efficient

Simple Portable
Platform-independent Architecture-neutral

Secure Concurrent
Interactive

Object-oriented Reliable

Distributed
For Internet

cs480(Prasad)

L4javaGoals

25

Simplicity
Programmer perspective
Automatic garbage collection
Avoids memory leaks. Avoids dangling pointers

No C++ structure/union.
Only pointer to structure.

Unconstrained array type

Implementer perspective
No multiple inheritance of code.
Only single inheritance of classes.

Restricted overloading.
cs480(Prasad) L4javaGoals 26

Garbage Collection : Perspectives


Garbage Collection is necessary for fully modular programming, to avoid introducing unnecessary intermodular dependencies.
Uniprocessor Garbage Collection Techniques by Paul R. Wilson et al

Two of the most powerful tools available to the software engineer are abstraction and modularity. ... Automatic memory management gives increased abstraction to the programmer.
Garbage Collection by Jones and Lin
cs480(Prasad) L4javaGoals 27

Portability
Architecture-neutral
Size of integer, char, etc. and the meaning of floating point operations fixed by the language.

All behavioral aspects of a Java program defined by the Java language specification, rather then left to the implementation.
Order of evaluation of operands fixed. Error and Exception handling
Imposes a degree of uniformity on the outcome of running a program.
cs480(Prasad) L4javaGoals 28

Non-portability : gotcha.c
main() int i { = 5; i); %d \n , %d printf( %d \n , printf( %d }

i, i/++i, i);

Intuitively??
5
cs480(Prasad)

6
L4javaGoals 29

class PortJava { public static void main(String[] args){ int i = 5; System.out.println( \t i = + + } } \t i/++i = \t i = + i + i/++i

+ i);

Output:: i = 5 i/++i = 0 i = 6

cs480(Prasad)

L4javaGoals

30

class PortableJava { public static void printOrder(int i,int j,int k) { System.out.print( \t i-> " + i); System.out.print( \t j-> " + j); System.out.println( \t k-> " + k); } public static void main(String[] args) { int i = 5; printOrder(i, i/++i, i); } }

Output:: i-> 5
cs480(Prasad)

j-> 0
L4javaGoals

k-> 6
31

Possible Outcomes
SPARC :
6 5 1 1 1
cc/gcc gotcha.c -ldl; a.out

6
cc/gcc gotcha.c; a.out

Alpha, MIPS : SUN-3 :


6

6
cc gotcha.c ; a.out

cs480(Prasad)

L4javaGoals

32

Object-oriented programming
Programming with Data Types
Data Abstraction
Modularity Encapsulation (information hiding)

Reuse and Sharing


Inheritance
Reusing code

Polymorphism and Dynamic binding


Sharing behavior; Frameworks
cs480(Prasad) L4javaGoals 33

Java Collections : Interfaces

cs480(Prasad)

L4javaGoals

34

Java Collections : Implementations


Implementations
Hash Table

Resizable Array

Balanced Tree TreeSet

Linked List

Set
Interfaces

HashSet

List Map
HashMap

ArrayList

LinkedList TreeMap

cs480(Prasad)

L4javaGoals

35

Reliability and Robustness


Reliability
Degree of Confidence in error-free execution of a program after a clean compile.

Strong typing

Robustness
Graceful degradation behavior of a program when presented with an input that violates preconditions. (Cf. correctness)

Exception handling
cs480(Prasad) L4javaGoals 36

Java : Compiler and Interpreter


source code javac bytecode java JIT native code

mips
cs480(Prasad)

pentium
L4javaGoals

sparc

alpha
37

Interpreted, Efficient, Secure


A Java program is compiled into bytecode that is interpreted by the Java Virtual m/c. Just-In-Time compilers convert bytecode into native code for efficiency. JVM performs various security checks while executing bytecode.
JVM enforces severe access restrictions while running applets downloaded from a remote site.
cs480(Prasad) L4javaGoals 38

Evolution of Sun s JDK


Java 1.0: Interpreter Java 1.1: Interpreter + JIT Compiler Java 2 : Hotspot
Profiling and Adaptive Dynamic Compilation of hot code Method in-lining and other aggressive optimizations, and Decompilation Improved Memory Management for long-running (server) programs Fast Thread Synchronization

cs480(Prasad)

L4javaGoals

39

Improvements : Java vs C++


Java is better than C++, more because of what it does not have, than for what it has. No global vars. No gotos.
Typos detected, not misinterpreted. Disciplined uses abstracted (exceptions, labeled breaks). Array-index out-of-bounds detected. In Java, pointers cannot be manipulated explicitly. However, they serve as object handles. No memory leaks and no illegal access of freed storage. Improves readability.

No pointers.

No explicit memory management.

cs480(Prasad)

L4javaGoals

40

Concurrent Programming
Threads can share address space. In Java, threads are modeled after Hoare s monitors. Java is a multi-threaded system, which is very convenient for coding interactive, multi-media applications.
Doing I/O concurrently with reading a document. (downloading via browser) Periodic updating of the screen with data acquired in real-time. (sports/stocks ticker)

cs480(Prasad)

L4javaGoals

41

Distributed Processing
WWW (URL+HTTP+HTML) contributed immensely to the sharing of (distributed) static data.
URL encodes description of a protocol, service, server name, location of a resource on the server, etc. succinctly.
http://www.cs.wright.edu/~tkprasad ftp://user@host:port/path mailto:user@host

URL facilitated access to remote resources by integrating access to various protocols/services such as FTP, telnet, mail, http, etc in a browser.

Java contributed immensely to the sharing of dynamic/executable content.


cs480(Prasad) L4javaGoals 42

(cont d)
CGI scripts enabled dynamic customization of responses based on user input (using FORMS).
However, this also requires a centralized, powerful server to run scripts to process client requests.

Java applets enabled moving code to a client machine in response to a client request (rather than the final data).
Computations distributed to client machines (providing an alternative to the traditional client-server model ). More responsive interaction, and emphasis on portability .
Required support for GUIs, network programming, virtual machine, etc.
cs480(Prasad) L4javaGoals 43

S-ar putea să vă placă și