1 / 76

Functional Programming

Functional Programming. Chapter 14. History of Functional Languages. Lisp is the second oldest language 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.

pancho
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 is the second oldest language • 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.

  3. 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, …

  4. 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

  5. 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 (ignoring imaginary numbers).

  6. 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

  7. 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

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

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

  10. Referential Transparency • Referential transparency: as in mathematics, a function’s result depends only upon the values of its parameters and not on any previous computation or the order of evaluation for its arguments. • In imperative programming results depend on the parameter values, and may also change the state (i.e., cause side effects): x = x + y; • lhs values versus rhs values • Functional programs accept and return data, but have no side effects.

  11. Lambda Calculus • The lambda calculus, invented in 1941, is the foundation of functional programming • Function specification without a name • e.g., (  x . x2 ) represents the Square function. Relate to mathematical notationf(x) = x2 • ((  x . x2 )2): apply the function to a value, similar to f(x) = x2 for x = 2

  12. 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.

  13. Pure Lambda Calculus* • Any identifier is a lambda expression. • If M and N are lambda expressions, then the application of M to N, written (M N), is a lambda expression • An abstraction, written (x∙M), where x is an identifier and M is a lambda expression, is also a lambda expression.

  14. BNFGrammar for  Expressions* • LambdaExpression variable | ( M N) | (  variable∙M ) • M  LambdaExpression • N  LambdaExpression

  15. Examples* • x a variable is a lambda exp • (x ∙ x)  variable∙M is a lambda exp (abstraction) • ((x ∙ x) (y ∙ y)) (M N) is a lambda exp (application) • In ( x∙M), x is bound. Other variables in M are free. • A bound variable has the same name as a parameter

  16. Bound Variables* • Bound variables act like function parameters in imperative languages, or variables in math functions. • They can be replaced (renamed) consistently with any variable that is free in M. • Doesn’t change meaning of lambda expression.

  17. Properties of Lambda Exp* • A substitution of expression N for all occurrences of a variable x in M is written M[x  N]. Examples:

  18. Beta Reductions(Function Application) • A beta reduction(( x . M)N) of the lambda expression ( x . M) is a substitution of all bound occurrences of x in M by N. e.g., (( x . x2)5) = 52 M = x2 and N = 5 • Beta reduction represents a single function application.

  19. Evaluations • Successive applications of beta-reductions: • ((λy· ((λ x · xyz)a))b) ⇒ ((λy· ayz)b) ⇒ abzor • ((λy· ((λ x · xyz)a))b) ⇒ ((λx · xbz)a) ⇒ abz • Evaluation (reduction) can be done in either order

  20. Pure v Applied Lambda Calculus • Pure lambda calculus:(( x . * x x)5) = (* 5 5) (* and 5 have no meaning other than as symbols) • Applied lambda calculus: (( x . * x x)5) = 25 • Functional languages = applied lambda calculus + constant values + built-in functions (operators) • e.g., (xyz) is a lambda expression; so is (x*y) or (*xy) • Functional languages use prefix notation

  21. When Are Arguments Evaluated? • Eager evaluation = beginning of the call • Advantage: efficiency • Disadvantage: possible runtime errors (if (= x 0) 1 (/ 1 x)) • Lazy evaluation = delaying argument evaluation until the argument is needed. • Advantage: flexibility and correctness • Lisp and Scheme use eager evaluation, Haskell uses lazy evaluation

  22. 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.

  23. 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.

  24. 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

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

  26. The define Function • Used to define global variables; e.g. • (define f 120) • definechanges its environment but is not equivalent to an assignment statement. It just assigns a global name to a value. • define can also be used for other purposes, as we will see. • setQ and setF are functions that operate more like assignments; also set!

  27. 14.2.2 Expression Evaluation • Three steps: • replace names of symbols by their current bindings. • Evaluate lists as function calls in Cambridge prefix.A list is a set of elements enclosed in ( )e.g., (* a 2) • The first element in the list is treated as the function • Constants evaluate to themselves.

  28. 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 #t ; predefined, true 5, #f, #t are constants, f is a bound symbol

  29. 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

  30. 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.

  31. 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

  32. 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:

  33. What is a Cons? • Each list node is a cons. • A record with two fields: the car and the cdr: car is the first field, cdr 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 the representation for an empty list.

  34. Dotted Lists • 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| • Lists are assumed to end with the value ( ) which is implemented by null reference • Some functions create dotted lists.

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

  36. Representing a List with a List as an Element This represents the list (a (b c)) a nil b nil c

  37. 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.

  38. 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

  39. List Functions • car: returns the first element (“head”) of a list • cdr: returns the tail of the list, which is itself a list • list: takes several arguments and returns a list made up of those arguments • append: takes two arguments and concatenates the second to the end of the first.

  40. 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) (cons 1 (cdr evens)) ; gives (1 2 4 6 8) (null? ‘()) ; gives #t, or true

  41. More Examples • (cdr(cdr evens)) ; (4 6 8) • (car ‘(6 8) ) ; 6 • The quote is necessary, otherwise Scheme would try to treat “6” as a function. • Since “evens” is already quoted, no need to repeat. • (cddr evens) is a shorthand notation for (cdr (cdr evens)). • Nest up to five cars and cdrs this way: (cadr), (caar), (cddar), etc.

  42. 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

  43. 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)

  44. 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.

  45. 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

  46. 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.

  47. Lisp conditional • COND is the original Lisp conditional statement and is sort of a cross between an if and a case • It takes a series of condition-result pairs • (cond ( (< x 0) (-x) )      ( (>= x 0) x )  )

  48. 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.

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

  50. Recursive functions • (define (factorial n) (if(<n1)1(*nfactorial(-n1))) )) • (define (fun1 alist) (if (null? alist) 0 (+ (car alist)(fun1(cdr alist)))))

More Related