Your SlideShare is downloading. ×
  • Like
Functional programming
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Functional programming

  • 456 views
Published

 

Published in Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
456
On SlideShare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
11
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. FUNCTIONAL PROGRAMMING REFERENCES: 1. PROGRAMMING LANGUAGES: PRINCIPLES AND PRACTICES. K. C. LAUDEN, SECOND EDITION 2. PROGRAMMING LANGUAGE PRAGMATICS. M. L. SCOTT AUGUST 31, 2011Thursday, September 8, 2011
  • 2. FUNCTIONAL PROGRAMMING REASONS TO STUDY FP: RECURSION ABSTRACTION HIGHER-ORDER FUNCTIONS > IMPACT MOST PROGRAMMING LANGUAGESThursday, September 8, 2011
  • 3. PROGRAMS AS FUNCTIONS PROGRAM ≡ DESCRIPTION OF A SPECIFIC COMPUTATION Y = F(X) F:X➝Y IN MATHEMATICS: *VARIABLES ≡ ACTUAL VALUES *NO MEMORY LOCATION CONCEPT. IN IMPERATIVE LANGUAGES: *VARIABLES ≡ MEMORY LOCATIONS + VALUESThursday, September 8, 2011
  • 4. PROGRAMS AS FUNCTIONS PROGRAM ≡ DESCRIPTION OF A SPECIFIC COMPUTATION Y = F(X) F:X➝Y IN MATHEMATICS: *VARIABLES ≡ ACTUAL VALUES *NO MEMORY LOCATION CONCEPT. IN IMPERATIVE LANGUAGES: *VARIABLES ≡ MEMORY LOCATIONS + VALUESThursday, September 8, 2011
  • 5. PROGRAMS AS FUNCTIONS CONSEQUENCES OF NO ASSIGNMENT OPERATION: *NO LOOPS *INSTEAD: RECURSION. IN FUNCTIONAL PROGRAMMING (PURE FUNCTIONAL PROGRAMMING): *NO VARIABLE > EXCEPT AS A NAME FOR A VALUE *NO ASSIGNMENT OPERATION > X = X + 1 DOES NOT MAKE ANY SENSE IN MATH! *ONLY CONSTANTS, PARAMETERS, AND VALUES.Thursday, September 8, 2011
  • 6. PROGRAMS AS FUNCTIONS EXAMPLE: ITERATIONS VS RECURSION VOID GCD ( INT U, INT V, INT * X ) INT GCD ( INT U, INT V ) { { INT Y, T, Z; IF ( V== 0 ) Z = U; RETURN U; Y = V; ELSE WHILE( Y != 0 ) RETURN GCD(V, U % V); { } T = Y; Y = Z % Y; Z = T; } *X = Z; }Thursday, September 8, 2011
  • 7. PROGRAMS AS FUNCTIONS CONSEQUENCES OF NO VARIABLES AND NO ASSIGNMENT OPERATION: *NO NOTION OF THE INTERNAL STATE OF A FUNCTION *THE VALUE OF ANY FUNCTION CANNOT DEPEND ON THE ORDER OF EVALUATION OF ITS ARGUMENTS >REFERENTIAL TRANSPARENCYThursday, September 8, 2011
  • 8. PROGRAMS AS FUNCTIONS CONSEQUENCES OF NO VARIABLES AND NO ASSIGNMENT OPERATION: *NO NOTION OF THE INTERNAL STATE OF A FUNCTION *THE VALUE OF ANY FUNCTION CANNOT DEPEND ON THE ORDER OF EVALUATION OF ITS ARGUMENTS >REFERENTIAL TRANSPARENCY *THE RUNTIME ENVIRONMENT ASSOCIATES NAMES TO VALUES ONLY; ONCE A NAME ENTERS THE ENVIRONMENT IT NEVER CHANGES >VALUE SEMANTICSThursday, September 8, 2011
  • 9. PROGRAMS AS FUNCTIONS IN FUNCTIONAL PROGRAMMING: *FUNCTIONS MUST BE GENERAL LANGUAGE OBJECTS > FIRST-CLASS VALUES *FUNCTIONS ≡ VALUES ⇒ CAN BE COMPUTED BY OTHER FUNCTIONS ⇒ WHICH CAN BE PARAMETERS TO FUNCTIONS. *FUNCTIONS CAN HAVE OTHER FUNCTIONS AS INPUT OR OUTPUT OR BOTH AS PARAMETERS > HIGHER-ORDER FUNCTIONSThursday, September 8, 2011
  • 10. PROGRAMS AS FUNCTIONS SUMMARY: 1. ALL PROCEDURES ARE FUNCTIONS AND CLEARLY DISTINGUISH INCOMING VALUES (PARAMETERS) FROM OUTGOING VALUES (RESULTS). 2. THERE ARE NO VARIABLES OR ASSIGNMENTS - VARIABLES ARE REPLACED BY PARAMETERS. 3. THERE ARE NO LOOPS - LOOPS ARE REPLACED BY RECURSIVE CALLS. 4. THE VALUE OF A FUNCTION DEPENDS ONLY ON THE VALUE OF ITS INPUT PARAMETERS AND NOT ON THE ORDER OF EVALUATION OR THE EXECUTION PATH THAT LED TO THE CALL. 5. FUNCTIONS ARE FIRST-CLASS VALUES.Thursday, September 8, 2011
  • 11. FUNCTIONAL PROGRAMMING IN AN IMPERATIVE LANGUAGE BASIC REQUIREMENT: 1. AVAILABILITY OF RECURSION 2. MECHANISM FOR IMPLEMENTING GENERAL FUNCTIONSThursday, September 8, 2011
  • 12. FUNCTIONAL PROGRAMMING IN AN IMPERATIVE LANGUAGE EXAMPLE: CONSIDER A FUNCTION THAT RETURNS THE SUM OF THE INTEGERS BETWEEN I AND J: SUM(I, J) = I + (I + 1) + (I + 2) + ... + (J - 1) + JThursday, September 8, 2011
  • 13. FUNCTIONAL PROGRAMMING IN AN IMPERATIVE LANGUAGE EXAMPLE: CONSIDER A FUNCTION THAT RETURNS THE SUM OF THE INTEGERS BETWEEN I AND J: SUM(I, J) = I + (I + 1) + (I + 2) + ... + (J - 1) + J INT SUM ( INT I, INT J ) { INT K, TEMP; TEMP = 0; FOR( K = I; K <= J; K++ ) TEMP += K; RETURN TEMP; }Thursday, September 8, 2011
  • 14. FUNCTIONAL PROGRAMMING IN AN IMPERATIVE LANGUAGE EXAMPLE: CONSIDER A FUNCTION THAT RETURNS THE SUM OF THE INTEGERS BETWEEN I AND J: SUM(I, J) = I + (I + 1) + (I + 2) + ... + (J - 1) + J INT SUM ( INT I, INT J ) INT SUM ( INT I, INT J ) { { INT K, TEMP; IF ( I > J ) TEMP = 0; RETURN 0; FOR( K = I; K <= J; K++ ) ELSE TEMP += K; RETURN I + SUM(I + 1, J); RETURN TEMP; } }Thursday, September 8, 2011
  • 15. FUNCTIONAL PROGRAMMING IN AN IMPERATIVE LANGUAGE TAIL RECURSION: LAST OPERATION IN A PROCEDURE CALLS ITSELF WITH DIFFERENT ARGUMENTS. AUTOMATIC RECURSIVE TO LOOP-CONVERSION: > REASSIGN PARAMETERS AND START OVER. INT GCD ( INT U, INT V ) { IF ( V== 0 ) RETURN U; ELSE RETURN GCD(V, U % V); }Thursday, September 8, 2011
  • 16. FUNCTIONAL PROGRAMMING IN AN IMPERATIVE LANGUAGE TAIL RECURSION: LAST OPERATION IN A PROCEDURE CALLS ITSELF WITH DIFFERENT ARGUMENTS. AUTOMATIC RECURSIVE TO LOOP-CONVERSION: > REASSIGN PARAMETERS AND START OVER. INT GCD ( INT U, INT V ) { INT T1, T2; /* TEMPS INTRODUCED BY TRANSLATOR */ FOR ( ; ; ) INT GCD ( INT U, INT V ) { IF (V == 0 ) { RETURN U; IF ( V== 0 ) ELSE RETURN U; { ELSE T1 = V; RETURN GCD(V, U % V); T2 = U % V; } U = T1; V = T2; } } }Thursday, September 8, 2011
  • 17. FUNCTIONAL PROGRAMMING IN AN IMPERATIVE LANGUAGE TAIL RECURSION: LAST OPERATION IN A PROCEDURE CALLS ITSELF WITH DIFFERENT ARGUMENTS. NOT SO AUTOMATIC RECURSIVE TO LOOP-CONVERSION: ACCUMULATING PARAMETERS > USED TO PRECOMPUTE OPERATIONS PERFORMED AFTER THE RECURSIVE CALL. EXAMPLE: SUM OF INTEGERS FROM I TO J. INT SUM ( INT I, INT J ) { IF ( I > J ) RETURN 0; ELSE RETURN I + SUM(I + 1, J); }Thursday, September 8, 2011
  • 18. FUNCTIONAL PROGRAMMING IN AN IMPERATIVE LANGUAGE TAIL RECURSION: LAST OPERATION IN A PROCEDURE CALLS ITSELF WITH DIFFERENT ARGUMENTS. NOT SO AUTOMATIC RECURSIVE TO LOOP-CONVERSION: ACCUMULATING PARAMETERS > USED TO PRECOMPUTE OPERATIONS PERFORMED AFTER THE RECURSIVE CALL. EXAMPLE: SUM OF INTEGERS FROM I TO J. INT SUM ( INT I, INT J ) INT SUM1 ( INT I, INT J, INT SUMSOFAR ) { { /* SUM1 IS CALLED A HELPING PROCEDURE */ IF ( I > J ) { IF (I > J ) RETURN 0; RETURN SUMSOFAR; ELSE ELSE RETURN I + SUM(I + 1, J); RETURN SUM1( I + 1, J, SUMSOFAR + I ); } } INT SUM( INT I, INT J ) { RETURN SUM1( I, J, 0 );}Thursday, September 8, 2011
  • 19. FUNCTIONAL PROGRAMMING IN AN IMPERATIVE LANGUAGE RESTRICTIONS OF IMPERATIVE LANGUAGES FOR FUNCTIONAL PROGRAMMING: 1. STRUCTURED VALUES SUCH AS ARRAYS AND RECORDS CANNOT BE RETURNED VALUES FROM FUNCTIONS. 2. THERE IS NO WAY TO BUILD A VALUE OF A STRUCTURED TYPE DIRECTLY. 3. FUNCTIONS ARE NOT FIRST-CLASS VALUES, SO HIGHER-ORDER FUNCTIONS CANNOT BE WRITTEN.Thursday, September 8, 2011
  • 20. FUNCTIONAL PROGRAMMING IN AN IMPERATIVE LANGUAGE RESTRICTIONS OF IMPERATIVE LANGUAGES FOR FUNCTIONAL PROGRAMMING: EXAMPLE: SORTING ARRAY IN C 1. AN ARRAY CANNOT BE RETURNED FROM A FUNCTION VALUE. 2. ANY ARRAY IS AUTOMATICALLY PASSED BY REFERENCE > SORT IN PLACE > VIOLATES THE RULE THAT THE INPUT OF A FUNCTION IN FP SHOULD ALWAYS BE DISTINGUISH FROM THE OUTPUT. *MOST PROBLEMATIC RESTRICTION: NON-FIRST-CLASSNESS OF FUNCTIONS IN IMPERATIVE LANGUAGES.Thursday, September 8, 2011
  • 21. FUNCTIONAL PROGRAMMING IN AN IMPERATIVE LANGUAGE EXAMPLE C CODE FOR A FUNCTION INT_ARRAY_MAX THAT COMPUTES THE MAXIMUM VALUE IN A NON-EMPTY ARRAY OF INTEGERS. INT INT_ARRAY_MAX ( INT A[], INT SIZE ) /* SIZE MUST BE > 0 */ { INT I, MAX = A[ 0 ]; FOR(I = 1; I < SIZE; I++) IF (MAX < A[ I ] ) MAX = A[ I ]; RETURN MAX; }Thursday, September 8, 2011
  • 22. FUNCTIONAL PROGRAMMING IN AN IMPERATIVE LANGUAGE EXAMPLE C CODE FOR A FUNCTIONAL VERSION OF THE INT_ARRAY_MAX FUNCTION. IT USES A HELPING PROCEDURE INT_ARRAY_MAX1 WITH RECURSION AND AN ACCUMULATING PARAMETER. INT INTMAX ( INT X, INT Y) { RETURN X > Y ? X : Y; } INT INT_ARRAY_MAX1 ( INT A[], INT SIZE, INT SOFAR ) { IF( SIZE == 0 ) RETURN SOFAR; ELSE RETURN INT_ARRAY_MAX1( A, SIZE - 1, INTMAX(SOFAR, A[SIZE-1])); } INT INT_ARRAY_MAX ( INT A[], INT SIZE ) /* SIZE MUST BE > 0 */ { RETURN INT_ARRAY_MAX1( A, SIZE - 1, A[ SIZE - 1 ]); }Thursday, September 8, 2011
  • 23. SCHEME: A DIALECT OF LISP LISP [LATE 1950 AND EARLY 1960] CREATED BY JOHN MCCARTHY FROM MIT LISP = LIST PROCESSOR BASED ON LAMBDA CALCULUS OF A. CHURCH. WAS AN INTERPRETER FOR AN IBM 704 FEATURES UNIFORM REPRESENTATION OF PROGRAMS AS DATA USING A SINGLE GENERAL DATA STRUCTURE - THE LIST. THE DEFINITION OF THE LANGUAGE USING AN INTERPRETER WRITTEN IN THE LANGUAGE ITSELF-CALLED A METACIRCULAR INTERPRETER. THE AUTOMATIC MANAGEMENT OF ALL MEMORY BY THE RUNTIME SYSTEM.Thursday, September 8, 2011
  • 24. THE ELEMENTS OF SCHEME THE CFG FOR SCHEME IS: EXPRESSION ➝ ATOM | LIST ATOM ➝ NUMBER | STRING | IDENTIFIER | CHARACTER | BOOLEAN LIST ➝ ‘(‘EXPRESSION-SEQUENCE’)’ EXPRESSION-SEQUENCE ➝ EXPRESSION EXPRESSION-SEQUENCE | EXPRESSION EXAMPLES OF SCHEME EXPRESSIONS: 47 -A NUMBER “HELLO” -A STRING #T -THE BOOLEAN VALUE TRUE #A -THE CHARACTER ‘A’ (2.1 3.5 7.2 4.2) -A LIST OF NUMBERS B -AN IDENTIFIER HELLO -AN IDENTIFIER (+ 2 4) -A LIST CONSISTING OF THE IDENTIFIER ‘+’ AND TWO NUMBERS (* (+ 2 4) (/ 6 2)) -A LIST CONSISTING OF AN IDENTIFIER FOLLOWED BY TWO LISTSThursday, September 8, 2011
  • 25. THE ELEMENTS OF SCHEME THE CFG FOR SCHEME IS: EXPRESSION ➝ ATOM | LIST ATOM ➝ NUMBER | STRING | IDENTIFIER | CHARACTER | BOOLEAN LIST ➝ ‘(‘EXPRESSION-SEQUENCE’)’ EXPRESSION-SEQUENCE ➝ EXPRESSION EXPRESSION-SEQUENCE | EXPRESSION SCHEME EVALUATION RULES [APPLICATIVE ORDER EVALUATION] 1. CONSTANT ATOMS, SUCH AS NUMBERS AND STRINGS EVALUATE TO THEMSELVES. 2. IDENTIFIERS ARE LOOKED UP IN THE CURRENT ENVIRONMENT AND REPLACED BY THE VALUE FOUND THERE. [DYNAMIC SYMBOL TABLE] 3. A LIST IS EVALUATED BY RECURSIVELY EVALUATING EACH ELEMENT IN THE LIST AS AN EXPRESSION; THE FIRST EXPRESSION IN THE LIST MUST EVALUATE TO A FUNCTION. THIS FUNCTION IS THEN APPLIED TO THE EVALUATED VALUES OF THE REST OF THE LIST.Thursday, September 8, 2011
  • 26. THE ELEMENTS OF SCHEME SCHEME EVALUATION RULES [APPLICATIVE ORDER EVALUATION] 1. CONSTANT ATOMS, SUCH AS NUMBERS AND STRINGS EVALUATE TO THEMSELVES. 2. IDENTIFIERS ARE LOOKED UP IN THE CURRENT ENVIRONMENT AND REPLACED BY THE VALUE FOUND THERE. [DYNAMIC SYMBOL TABLE] 3. A LIST IS EVALUATED BY RECURSIVELY EVALUATING EACH ELEMENT IN THE LIST AS AN EXPRESSION; THE FIRST EXPRESSION IN THE LIST MUST EVALUATE TO A FUNCTION. THIS FUNCTION IS THEN APPLIED TO THE EVALUATED VALUES OF THE REST OF THE LIST. EXAMPLES: EVALUATE 47 “HELLO” #T #A (2.1 3.5 7.2 4.2) B HELLO (+ 2 4) (* (+ 2 4) (/ 6 2))Thursday, September 8, 2011
  • 27. THE ELEMENTS OF SCHEME BUILT-IN FUNCTIONS QUOTE: PREVENTS EVALUATION: >(2.1 3.4 5.6) ERROR: THE OBJECT 2.1 IS NOT A PROCEDURE >(QUOTE (2.1 3.4 5.6)) (2.1 3.4 5.6) IF: IF-THEN-ELSE CONSTRUCT (IF (=A 0 ) 0 (/ 1 A)) COND: IF-ELSEIF CONSTRUCT (COND((= A 0) 0) ((= A 1) 1) (ELSE (/ 1 A))) SEMANTICS OF (IF EXP1 EXP2 EXP3): EXP1 EVALUATES FIRST IF EXP1 EVALUATES TO FALSE (#F), THEN EXP3 IS EVALUATED; THEN EXP2 IS EVALUATED AND RETURNED. IF EXP3 IS ABSENT AND EXP1 EVALUATES TO FALSE, THEN THE VALUE OF THE EXPRESSION IS UNDEFINED.Thursday, September 8, 2011
  • 28. THE ELEMENTS OF SCHEME SEMANTICS OF (IF EXP1 EXP2 EXP3): EXP1 EVALUATES FIRST IF EXP1 EVALUATES TO FALSE (#F), THEN EXP3 IS EVALUATED; THEN EXP2 IS EVALUATED AND RETURNED. IF EXP3 IS ABSENT AND EXP1 EVALUATES TO FALSE, THEN THE VALUE OF THE EXPRESSION IS UNDEFINED. SEMANTICS OF (COND EXP1 EXP2 ... EXPN): EACH EXPI MUST BE A PAIR EXPI = (FST SND). EACH EXPRESSION EXPI IS CONSIDERED IN ORDER, AND THE FIRST PART OF IT IS EVALUATED. IF FST EVALUATES TO TRUE, THEN SND IS EVALUATED AND ITS VALUE IS RETURNED BY THE COND EXPRESSION. IF NONEN OF THE CONDITIONS EVALUATE TO TRUE, THEN THE EXPRESSION IN THE ELSE IS EVALUATED AND RETURNED. DELAYED EVALUATION:Thursday, September 8, 2011
  • 29. THE ELEMENTS OF SCHEME BUILT-IN FUNCTIONS > (LET ((A 2) (B 3)) (+ A B)) ; BINDING LIST 5Thursday, September 8, 2011
  • 30. THE ELEMENTS OF SCHEME FUNCTION DEFINITION (DEFINE A 2) (DEFINE EMPTYLIST ‘()) (DEFINE (GCD U V) ; FUNCTION NAME AND PARAMETERS (IF (= V 0) ; FUNCTION BODY U (GCD V (REMAINDER U V))))Thursday, September 8, 2011
  • 31. THE ELEMENTS OF SCHEME BUILT-IN FUNCTIONS FOR I/O: READ AND DISPLAY >(READ) >(DISPLAY “HELLO WORLD”) >(DISPLAY 234) SEE PAGE 486 FOR A COMPLETE EXAMPLE WITH I/OThursday, September 8, 2011
  • 32. DATA STRUCTURES IN SCHEME BASIC DATA STRUCTURE: LIST *EVERYTHING ELSE SHOULD BE PUT IN THAT FORMAT!!! EXAMPLE: BINARY SEARCH TREE NODE IS (NAME LEFT RIGHT) (“HORSE” (“COW” () (“DOG” () ())) (“ZEBRA” (“YAK” () ()) () )) “HORSE” “COW” “ZEBRA” () “DOG” “YAK” () () ()Thursday, September 8, 2011
  • 33. DATA STRUCTURES IN SCHEME BASIC OPERATIONS ON LIST: >(CAR L) >(CONS L) BINARY TREE: (DEFINE (LEFTCHILD B) (CAR ( CDR B))) (DEFINE (RIGHTCHILD B) (CAR (CDR (CDR B)))) (DEFINE (DATA B) (CAR B)) TREE TRAVERSAL: (DEFINE (PRINT-TREE B) (COND ((NULL? B) ‘() ) (ELSE (PRINT-TREE (LEFTCHILD B)) (DISPLAY (DATA B)) (NEWLINE) (PRINT-TREE (RIGHTCHILD B)))))Thursday, September 8, 2011
  • 34. PROGRAMMING TECHNIQUES IN SCHEME EXAMPLE: SQUARING THE NUMBERS IN A LIST (DEFINE (SQUARE-LIST L) (IF (NULL? L) ‘() (CONS (* (CAR L) (CAR L)) (SQUARE-LIST (CDR L))))) EXAMPLE: PRINTING OUT THE SQUARES OF INTEGERS FROM 1 TO N (DEFINE (PRINT-SQUARES LOW HIGH) (COND ((> LOW HIGH) ‘()) (ELSE (DISPLAY(* LOW LOW)) (NEWLINE) (PRINT-SQUARES (+ 1 LOW) HIGH))))Thursday, September 8, 2011
  • 35. Delayed Evaluation An expression subject to lazy evaluation is not evaluated until its value is required and once is evaluated is never reevaluated. delay force used only in the absence of side effects: the order of evaluation is unimportant. benefits: some amount of computation might be avoided altogether if it is delayed until absolutely required. stream (infinite lists) constructionThursday, September 8, 2011
  • 36. Delayed Evaluation Use language R5RS (define stream-car (lambda (s) (car (force s)))) (define stream-cdr (lambda (s) (cdr (force s)))) (define counters (let next ((n 1)) (delay (cons n (next (+ n 1)))))) (stream-car counters)Thursday, September 8, 2011
  • 37. Delayed Evaluation Use Language R5RS from DrRacket (stream-car (stream-cdr counters)) (define stream-add (lambda (s1 s2) (delay (cons (+ (stream-car s1) (stream-car s2)) (stream-add (stream-cdr s1) (stream-cdr s2)))))) (define even-counters (stream-add counters counters)) (stream-car even-counters) (stream-car (stream-cdr even-counters))Thursday, September 8, 2011
  • 38. Exercises Write recursive functions in Scheme for: 1. The nth Fibonacci number. 2. The sum of the nth first natural numbers. 3. The factorial of n. 4. Reversing a list of elements. 5. Computing the number of elements in a list.Thursday, September 8, 2011