1 / 68

Functional Programming

Functional Programming. Chapter 14. History of Functional Languages. Lisp, a functional programming language, is the second oldest language (next to Fortran). Motivated by a need to do symbolic, rather than numerical, manipulations.

newman
Download Presentation

Functional Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Functional Programming Chapter 14

  2. History of Functional Languages • Lisp, a functional programming language, is the second oldest language (next to Fortran). • Motivated by a need to do symbolic, rather than numerical, manipulations. • Common LISP and Scheme are the two most popular dialects of the traditional LISP. • Haskell is a modern functional language that adds strong typing to the more usual features. • Other new functional languages: Erlang, Scala, Ocaml, …

  3. Scala • The name comes from Scalable Language • Combines functional programming with OO concepts. • Runs on the Java virtual machine • Created by Martin Odersky • Basis for many well-known systems today including Twitter, FourSquare and LinkedIn • Coursera has offered free online courses in Scala

  4. History/Characteristics • LISt Processing • The linked list is the major data structure • Both programs and data can be represented this way • Programs are able to manipulate code just like any other data • Learning programs, …

  5. Statement of Purpose • “The Lisp language is primarily for symbolic data processing. It has been used for symbolic calculations in differential and integral calculus, electrical circuit design, mathematic logic, game playing, and other fields of artificial intelligence.”, 1965, from the LISP 1.5 Programmer’s Manual

  6. Background: Functions • A function f from a set X (the domain) to a set Y (the range) maps each element x in X to a unique element y in Y. • For example, f(x) = x2 maps the set of real numbers into the set of positive real numbers. • i.e., the domain X is the set of all real numbers, the range is the set of positive reals.

  7. Background: Functional Composition • If f is a function from X to Y and g is a function from Y to Z, then (g ◦ f ) (x) is a function from X to Z defined as(g ◦ f ) (x) = g(f (x)), for all x in XSimply put, it means to replace the x in g(x) with f (x). • Example: • f (x) = x2+ x • g(x) = 2x + 1 • g ◦ f = 2(x2 + x )+ 1

  8. Overview • Functional programming mirrors mathematical functions: • domain = input, range = output • A computation maps inputs to outputs • Variables are mathematical symbols; not associated with memory locations. • Compare to imperative programming where a variable represents a value that is stored in memory and can be accessed by name as long as it is alive and in scope. • In functional languages a symbol is used in a computation of a value that then can be used in additional computations.

  9. Overview • Pure functional programming is state-free: no assignment statements. • Programs in pure functional languages consist of composite functions; output of each function becomes input to another. • Today, most functional languages have some imperative statements.

  10. 14.1 Functions and the Lambda Calculus • Typical mathematical function: Square(n) = n2 • funcName(args) = func-definition: an expression • Square : R R maps from reals to positive reals • A function is total if it is defined for all values of its domain. Otherwise, it is partial. e.g., Square is total.

  11. Semantics of Variables • Functional languages adopt the mathematical notion of a variable as something that represents an expression. • There is no association with a memory location or modification of a variable’s value. • So in functional languages a variable represents an immutable value; since variables don’t get updated, there’s no concept of assignment.

  12. Semantics of Variables • Since there is no assignment statement, the concept of program state is also meaningless. • Contrast to the view of functions in imperative languages, where function values are based on arguments, order of evaluation, and can also have side effects (change state). • Pure functional languages have no state in the sense of state & so no side effects.

  13. Referential Transparency • Referential transparency: a function’s result depends only upon the values of its arguments and not on any previous computation or the order of evaluation of its arguments. • However, most functional languages today are not “pure”; they have some version of the assignment statement.

  14. Lambda Calculus • The lambda calculus, invented in 1941, is the foundation of functional programming • It “…provides simple semantics for computation with functions so that properties of functional computation can be studied.”http://www.answers.com/topic/lambda-calculus#Motivation

  15. Lambda Calculus • Is a general model of computation • Can express anything that can be expressed by a Turing machine; in other words, is Turing Complete • An imperative language works by changing the data store; a functional language works by applying functions and returning values • Lambda calculus models the latter approach • Some practitioners claim that it is harder to make mistakes while using this style of programming.

  16. Status of Functions • In imperative and OO programming, functions have different (lower) status than variables. • In functional programming, functions have same status as variables; they are first-class entities. • They can be passed as arguments in a call. • They can transform other functions.

  17. Example • A function that operates on other functions is called a functional form. e.g., g(f, [x1, x2, … ]) = [f(x1), f(x2), …], becomes g(Square, [2, 3, 5]) = [4, 9, 25] • Meaning: function g takes as parameters another function and a list (sequence) of values to which the parameter function is applied.

  18. Programs as Lists • Lists are written with white-space-separated elements enclosed in parentheses • Expressions are represented as lists • Lists are treated as functions with the first element being the operation and the remaining elements the arguments.

  19. 14.2 Scheme • A derivative of Lisp • Our subset: • omits assignments • simulates looping via recursion • simulates blocks via functional composition • Scheme is Turing complete, even without while statements – recursion is used for repetition.

  20. 14.2.1 Expressions • Cambridge prefix notation for all Scheme expressions: (f x1 x2 …xn) • e.g., • (+ 2 2) ; evaluates to 4 • (+(* 5 4 2)(-6 2));means 5*4*2+(6-2) • Note: Scheme comments begin with ; • Cambridge prefix allows operators to have an arbitrary number of arguments.

  21. The define Function • Used to define global “variables”; e.g. • (define f 120) • defineis not equivalent to an assignment statement. It just gives a name to a value as a convenient notation. • define can also be used for other purposes, as we will see. • setQandsetFare functions that operate more like assignments.

  22. 14.2.2 Expression Evaluation • Three steps: • replace names of symbols by their current bindings. • Evaluate lists as function calls in Cambridge prefix, where a list is a set of elements enclosed in ( ); e.g., (* f 2 ) • The first element in the list is always treated as the function unless you specifically say not to. • Constants evaluate to themselves.

  23. Examples 5 ; evaluates to 5 Given the global definition (define f 120) then f ; evaluates to 120 (+ f 5) ; evaluates to 125 (+ 5 2 9 13) ; evaluates to 29 #f ; predefined, false 5, #f, #t are constants, f is a bound symbol

  24. Lists as Function Calls • (+ 5 2 9 13) ; evaluates to 29but • (+ (5 2 9 13)); an errorScheme will try to evaluate the second list, interpreting “5” as a function • (f);error - f isn’t a function

  25. Preventing Evaluation (define colors (quote (red yellow green)))or (define colors (‘ (red yellow green))) Quoting tells Scheme/LISP that the following list is not to be evaluated. This is a way of defining data.

  26. Quoted Lists (define x f) ; defines x as 120 (value of f) (define x ‘f) ; defines x as the symbol f (define color ‘red) ; color is defined to be red (define color red) ; error: no definition of red

  27. 14.2.3 Lists • A list is a series of expressions enclosed in parentheses. • Lists represent both functions and data. • The empty list is written (). • e.g., (0 2 4 6 8) is a list of even numbers. • Here’s how it’s stored:

  28. List Node Structure • Each list node is a record with two fields: the car and the cdr: car is (a pointer to) the first field, cdr is (a pointer to)the second. • Note that in the previous example the cdr of the last node ( |8|nil| ) is nil. • This is equivalent to the null pointer in C++ • The nil value can be represented as ( ), which is also the representation for an empty list.

  29. “Proper” Lists & Dotted Lists • Proper lists are assumed to end with the value( ) which is implemented by null reference • In a dotted list the last cons has some value other than nil as the value of the cdr field. • “Dotted” lists are written (0 2 4 6 . 8) The last node in the previous list would have been |6|8| • A cons cell is a cell that consists of two values, as opposed to a value and a pointer.

  30. Structure of a List in Scheme Figure 14.1 (a) Notice the difference between the list with nil as the last entry, and the “dotted” list shown in part b. (b)

  31. List Elements Can Be Lists Themselves This represents the list (a (b c)) a nil b nil c

  32. Lists as Binary Trees • Because each node in a Scheme list consists of two pointers, internally the lists are similar to binary trees. • Recall; • The links (pointers) are called the 'car' and the 'cdr'. • A list node (cell) is also called a cons or a pair.

  33. List Functions • car: returns the first element (“head”) of a list • cdr: returns the tail of the list, which is itself a list

  34. List Transforming Functions • Suppose we write (define evens ‘(0 2 4 6 8)). Then: (car evens) ; gives 0 (cdr evens) ; gives (2 4 6 8) ( (null? ‘()) ; gives #t, or true (cdr(cdr evens)); (4 6 8) (car‘(6 8)) ; 6 (quoted to stop eval)

  35. List Functions • cons: used to build lists • Requires two arguments: an element and a list; e.g., • (cons 8 ( )) ; gives the 1-element list (8) • (cons 6 (cons 8( ))) ; gives the list (6 8) • (cons 6 ‘(8)) ; also gives the list (6 8) • (cons 4(cons 8 9)) ; gives the dotted list ; (4 8 . 9 ) since 9 is not a ; list

  36. List Building Functions • list takes an arbitrary number of arguments and creates a list; append takes two lists and concatenates them: • (append ‘(1 3 5) evens) ;gives(1 3 5 0 2 4 6 8) • (append evens (list 3) ; gives (0 2 4 6 8 3) • (list ‘(1 3 5) evens) ; gives ((1 3 5) (0 2 4 6 8)) • (list 1 2 3 4) ; gives (1 2 3 4) • (list ‘evens ‘odds) ;gives (evens odds)

  37. Equal • The functionequal?returns true if the two objects have the same structure and content. (equal? 5 ‘(5)) ; gives #f, or false (equal? 5 5) ; #t (equal? ‘(1 2 3) ‘(1 (2 3))) ; returns false

  38. 14.2.4 – Elementary Values • Numbers: integers, rationals, and floating point numbers • Characters • Functions • Symbols • Strings • Boolean values #t and #f • All values except #f and ( ) are interpreted as true when used as a predicate.

  39. Control Flow (if test then-part) (if test then-part else-part) Example: (if (< x 0) (- 0 x)) ;returns –x if x<0 (if (< x y) x y) ; returns the smaller of x, y

  40. Control Flow • The casestatement is similar to a Java or C++ switch statement: • (case month (( sep apr jun nov) 30) ((feb) 28) (else 31) ; optional ) • All cases take an unquoted list of constants, except for the else.

  41. Defining Functions • define is also used to define functions; according to the following syntax:(definename(lambda(arguments)body))or(define(namearguments)body) • From the former, one can see that Scheme is an applied lambda calculus.

  42. Examples • (define (min x y) (if (< x y) x y))name args bodyto return the minimum of x and y • (define (abs x)(if(< x 0)(- 0 x) x))to find the absolute value of x

  43. ;; bulls-eye? : Number Number -> Boolean ;; determines if (x,y) is in the bull's eye (define (bulls-eye? x y) (<= (dist-to-origin x y) 5)) name args body ;; dist-to-origin : Number Number -> Number ;; determines distance from (0,0) to (x,y) (define (dist-to-origin x y) (sqrt (+ (* x x) (* y y)))) name args body

  44. Recursive functions • (define (factorial n) (if(<n1)1(*nfactorial(-n1))) )) • (define (fun1 alist) (if (null? alist) 0 (+ (car alist)(fun1(cdralist))))) • Suppose ‘alist’ is replaced by ‘evens’

  45. Built-in Functions • length: returns the number of elements in a list • (length ‘(1 2 3 4)) ; returns 4 • (length ‘((1 2 3) (5 6 7) 8)) ; returns 3 • (define (length alist) (if (null? alist) 0 (+ 1 (length (cdr alist)))))

  46. Built-in Functions • member: tests whether an element is in a list(member 4 evens);returns(468)(member 1 ‘(4 2)); returns () • If the element is in the list, return portion of the list starting with that element, else return the empty list.

  47. Functions as Parameters • The mapcarfunction takes two parameters: a function fun and a list alist. • mapcar applies the function to the list of values, one at a time, and returns a list of the results.

  48. Functions as Parameters (define (mapcar fun alist) (if (null? alist) ‘( ) (cons (fun (car alist)) (mapcar fun (cdralist))) )) E.g., if (define (square x) (* x x)) then (mapcar square ‘(2 3 5 7 9)) returns (4 9 25 49 81)

  49. 14.2.9 Symbolic Differentiation • Symbolic Differentiation Rules • Fig 14.2

  50. (define (diff x expr) (if (not (list? expr)) (if (equal? x expr) 1 0) (let ((u (cadr expr)) (v (caddr expr))) (case (car expr) ((+) (list ‘+ (diff x u) (diff x v))) ((-) (list ‘- (diff x u) (diff x v))) ((*) (list ‘+ (list ‘* u (diff x v)) (list ‘* v (diff x u)))) ((/) (list ‘div (list ‘- (list ‘* v (diff x u)) (list ‘* u (diff x v))) (list ‘* u v))) ))))

More Related