Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 15 Functional Programming Languages

Similar presentations


Presentation on theme: "Chapter 15 Functional Programming Languages"— Presentation transcript:

1 Chapter 15 Functional Programming Languages
순천향대학교 컴퓨터공학과 하 상 호

2 Chapter 15 Topics Introduction Mathematical Functions
Fundamentals of Functional Programming Languages The First Functional Programming Language: LISP Introduction to Scheme Support for Functional Programming in Primarily Imperative Languages Comparison of Functional and Imperative Languages

3 Introduction The design of the imperative languages is based directly on the von Neumann architecture Efficiency is the primary concern, rather than the suitability of the language for software development The design of the functional languages is based on mathematical functions A solid theoretical basis that is also closer to the user, but relatively unconcerned with the architecture of the machines on which programs will run

4 Introduction One of the fundamental characteristics of program written in imperative languages is that they have state, which changes throughout the execution process. This state is represented by the program’s variables. The author and all readers of the program must understand the uses of its variables and how the program’s state changes through execution. For a large program, this is a daunting task. This is one problem with programs written in an imperative language that is hot present in a program written in a pure functional language, for such programs have neither variables nor state.

5 Introduction LISP began as a pure functional language but soon acquired some important imperative features that increased its execution efficiency. It dominates in the areas of knowledge representation, machine learning, intelligent training systems, and the modeling of speech. Common LISP is amalgam of several early 1980s dialects of LISP Scheme is a small, static-scoped dialect of LISP. It has been widely used to teach functional programming. It is also used in some universities to teach introductory programming courses The development of the typed functional programming languages, primarily ML, Haskell, OCaml, and F#, has led to a significant expansion of the areas of computing in which functional languages are now used. As these languages have matured, their practical is growing. They are now being used in areas such as database processing, financial modeling, statistical analysis, and bio-informatics.

6 Mathematical Functions
A mathematical function is a mapping of members of one set, called the domain set, to another set, called the range set The mapping is described by an expression or by a table Functions are often applied to a particular element of the domain set. Note that the domain set may be the cross product of several sets(reflecting that there can be more than one parameter) A function yields an element of the range set

7 Mathematical Functions
Fundamental characteristics The evaluation order of their mapping expressions is controlled by recursion and conditional expressions, rather than by the sequencing and iterative repetition Because they have no side effects and cannot depend on any external values, they always map a particular element of the domain to the same element of the range. However, a subprogram in an imperative language may depend on the current values of several nonlocal or global variables. This makes it difficult to determine statically what values the subprogram will produce and what side effects it will have on a particular execution

8 Mathematical Functions
In mathematics, there is no such thing as a variable that models a memory location. Local variable in functions in imperative P.L. maintain the states of the function. Computation is accomplished by evaluating expression in assignment statements that change the state of the program. In mathematics, there is no concept of the state of a function. Mathematical function maps its parameter(s) to a value(or values), rather than specifying a sequence of operations on values in memory to product a value.

9 Simple Functions They are often written as function name, followed by a list of parameters in parentheses, followed by the mapping expression Ex. cube(x) = x * x * x The domain and range sets are the real numbers ≡ is used to mean “is defined as” The parameter x can represent any member of the domain set, but it is fixed to represent one specific element during evaluation of the function expression

10 Simple Functions Function applications are specified by pairing the function name with a particular element of the domain set The range element is obtained by evaluating the function-mapping expression with the domain element substituted for the occurrences of the parameter During evaluation, the mapping of a function contains no unbound parameters, where a bound parameter is a name for a particular value. Every occurrence of a parameter is bound to a value from the domain set and is a constant during evaluation

11 Simple Functions Function applications are specified by pairing the function name with a particular element of the domain set Ex. cube(x) = x * x * x x is bound to 2.0 during the evaluation and there are no unbound parameters x is a constant(its value cannot be changed) during the evaluation

12 Lambda Expressions Lambda notation, as devised by Alonzo Church(1941), provides a method for defining nameless functions A lambda expression specifies the parameter(s) and the mapping of a function in the following form (x) x * x * x for the function cube(x) = x * x * x Lambda expressions describe nameless functions

13 Lambda Expressions Lambda expressions are applied to parameter(s) by placing the parameter(s) after the expression e.g., ((x) x * x * x)(2) which evaluates to 8

14 Functional Forms A higher-order function, or functional form, is one that either takes functions as parameters or yields a function as its result, or both

15 Function Composition A functional form that takes two functions as parameters and yields a function whose value is the first actual parameter function applied to the application of the second Form: h  f ° g which means h (x)  f ( g ( x)) For f (x)  x + 2 and g (x)  3 * x, h  f ° g yields (3 * x)+ 2

16 Apply-to-all A functional form that takes a single function as a parameter and yields a list of values obtained by applying the given function to each element of a list of parameters Form:  For h(x)  x * x (h, (2, 3, 4)) yields (4, 9, 16)

17 Fundamentals of Functional Programming Languages
The objective of the design of a FPL is to mimic mathematical functions to the greatest extent possible The basic process of computation is fundamentally different in a FPL than in an imperative language In an imperative language, operations are done and the results are stored in variables for later use Management of variables is a constant concern and source of complexity for imperative programming In an FPL, variables are not necessary, as is the case in mathematics Referential Transparency - In an FPL, the evaluation of a function always produces the same result given the same parameters

18 LISP Data Types and Structures
Data object types: originally only atoms and lists List form: parenthesized collections of sublists and/or atoms e.g., (A B (C D) E) Originally, LISP was a typeless language LISP lists are stored internally as single-linked lists

19 LISP Interpretation Lambda notation is used to specify functions and function definitions. Function applications and data have the same form. e.g., If the list (A B C) is interpreted as data it is a simple list of three atoms, A, B, and C If it is interpreted as a function application, it means that the function named A is applied to the two parameters, B and C The first LISP interpreter appeared only as a demonstration of the universality of the computational capabilities of the notation Is a universal function that could evaluate any other function

20 Origins of Scheme A mid-1970s dialect of LISP Uses only static scoping
Developed at MIT by Sussman and Steele in 1975 designed to be a cleaner, more modern, and simpler version than the contemporary dialects of LISP Uses only static scoping Functions are first-class entities They can be the values of expressions and elements of lists They can be assigned to variables, passed as parameters, and returned from functions

21 The Scheme Interpreter
In interactive mode, the Scheme interpreter is an infinite read-evaluate-print loop (REPL) It repeatedly reads an expression typed by the user, interprets the expression, and displays the resulting value This form of interpreter is also used by Python and Ruby Expressions are interpreted by the function EVAL Literals evaluate to themselves Expressions that are calls to primitive functions are evaluated in the following way: First, each of the parameter expressions is evaluated, in no particular order Then, the primitive function is applied to the parameter values, and the resulting value is displayed

22 Primitive Function Evaluation
Parameters are evaluated, in no particular order The values of the parameters are substituted into the function body The function body is evaluated The value of the last expression in the body is the value of the function

23 Primitive Functions Primitive Arithmetic Functions: +, -, *, /, ABS, SQRT, REMAINDER, MIN, MAX expression value 42 42 (* 3 7) 21 ( ) 20 (- 5 6) -1 ( ) 6 (- 24 (* 4 3))12

24 LAMBDA Expressions Lambda Expressions Form is based on  notation
e.g., (LAMBDA (x) (* x x) is a nameless function x is called a bound variable within the lambda expression Lambda expressions can be applied to parameters e.g., ((LAMBDA (x) (* x x)) 7) a bound variable, x, is bound to 7 during the evaluation it never changes in the expression after being bound to an actual parameter value at the time evaluation of the lambad expression begins LAMBDA expressions can have any number of parameters (LAMBDA (a b c x) (+ (* a x x) (* b x)c))

25 Special Form Function: DEFINE
DEFINE - Two forms: To bind a symbol to an expression e.g., (DEFINE pi ) Example use: (DEFINE two_pi (* 2 pi)) These symbols are not variables – they are like the names bound by Java’s final declarations To bind names to lambda expressions (LAMBDA is implicit) form: (DEFINE (function_name parameters) (expression) ) e.g., (DEFINE (square x) (* x x)) Example use: (square 5) - The evaluation process for DEFINE is different! The first parameter is never evaluated. The second parameter is evaluated and bound to the first parameter.

26 Special Form Function: DEFINE
Ex. (DEFINE (square x) (* x x)) (DEFINE (hypotenuse side1 side2) (SQRT(+ square side1)(square side2))

27 Output Functions Usually not needed, because the interpreter always displays the result of a function evaluated at the top level (not nested) Scheme has a formatted output function PRINTF, which is similar to the printf function of C Note: explicit input and output are not part of the pure functional programming model, because input operations change the state of the program and output operations are side effects

28 Numeric Predicate Functions
#T (or #t) is true and #F (or #f) is false (sometimes () is used for false) =, <>, >, <, >=, <= EVEN?, ODD?, ZERO?, NEGATIVE? The NOT function inverts the logic of a Boolean expression

29 Control Flow Selection- the special form, IF
(IF predicate then_exp else_exp) (IF (<> count 0) (/ sum count) ) (DEFINE (factorial n) (IF (<= n 1) 1 (* n (factorial (- n 1))) ))

30 Control Flow Recall from Chapter 8 the COND function: support multiple selections (DEFINE (leap? year) (COND ((ZERO? (MODULO year 400)) #T) ((ZERO? (MODULO year 100)) #F) (ELSE (ZERO? (MODULO year 4))) ))

31 Scheme’s Multiple Selector
General form of a call to COND: (COND (predicate1 expression1) (predicaten expressionn) [(ELSE expressionn+1)] ) The ELSE clause is optional; ELSE is a synonym for true Each predicate-expression pair is a parameter - Semantics: The value of the evaluation of COND is the value of the expression associated with the first predicate expression that is true

32 List Functions QUOTE - takes one parameter; returns the parameter without evaluation QUOTE is required because the Scheme interpreter, named EVAL, always evaluates parameters to function applications before applying the function. QUOTE is used to avoid parameter evaluation when it is not appropriate such as data element QUOTE can be abbreviated with the apostrophe prefix operator '(A B) is equivalent to (QUOTE (A B)) ‘(A) returns A ‘(A B C) returns (A B C) Recall that CAR, CDR, and CONS were covered in Chapter 6

33 List Types Lists in LISP and Scheme are delimited by parentheses and use no commas (A B C D) and (A (B C) D) Data and code have the same form As data, (A B C) is literally what it is As code, (A B C) is the function A applied to the parameters B and C The interpreter needs to know which a list is, so if it is data, we quote it with an apostrophe ′(A B C) is data

34 List Types (continued)
List Operations in Scheme CAR returns the first element of its list parameter (CAR ′(A B C)) returns A CDR returns the remainder of its list parameter after the first element has been removed (CDR ′(A B C)) returns (B C) - CONS puts its first parameter into its second parameter, a list, to make a new list (CONS ′A (B C)) returns (A B C) LIST returns a new list of its parameters (LIST ′A ′B ′(C D)) returns (A B (C D))

35 List Functions (continued)
Examples: (CAR ′((A B) C D)) returns (A B) (CAR ′A) is an error (CDR ′((A B) C D)) returns (C D) (CDR ′A) is an error (CDR ′(A)) returns () (CDR ‘()) is an error (CONS ′() ′(A B)) returns (() A B) (CONS ′(A B) ′(C D)) returns ((A B) C D) (CONS (CAR x) (CDR x)) = ? Where x is a list (CONS ′A ′B) returns (A . B) (a dotted pair)

36 List Functions (continued)
Some of the most commonly use functional compositions are built in as single functions (CAAR x) ≡ (CAR (CAR x)) (CADR x) ≡ (CAR (CDR x)) (CADDAR x) ≡ (CAR (CDR (CDR (CAR x)))) (CADDAR ‘((A B (C) D) E)) = ?

37 List Functions (continued)
LIST is a function for building a list from any number of parameters (LIST ′apple ′orange ′grape) returns (apple orange grape) (CONS ′apple (CONS ′orange (CONS ′grape ‘())))

38 Predicate Function: EQ?
EQ? takes two expressions as parameters (usually two atoms); it returns #T if both parameters have the same pointer value; otherwise #F (EQ? 'A 'A) yields #T (EQ? 'A 'B) yields #F (EQ? 'A '(A B)) yields #F (EQ? '(A B) '(A B)) yields #T or #F (EQ? 3.4 ( ))) yields #T or #F

39 Predicate Function: EQV?
EQV? is like EQ?, except that it works for both symbolic and numeric atoms; it is a value comparison, not a pointer comparison (EQV? 3 3) yields #T (EQV? 'A 3) yields #F (EQV 3.4 ( )) yields #T (EQV? 3.0 3) yields #F (floats and integers are different)

40 Predicate Functions: LIST? and NULL?
LIST? takes one parameter; it returns #T if the parameter is a list; otherwise #F (LIST? '()) yields #T NULL? takes one parameter; it returns #T if the parameter is the empty list; otherwise #F (NULL? '(())) yields #F

41 Example Scheme Function: member
member takes an atom and a simple list; returns #T if the atom is in the list; #F otherwise A simple list does not include sublists (member ‘B ‘(A B C)) returns #T (member ‘B ‘(A C D E)) returns #F How to define member?

42 Example Scheme Function: member
Define member DEFINE (member atm a_list) (COND ((NULL? a_list) #F) ((EQ? atm (CAR lis)) #T) ((ELSE (member atm (CDR a_list))) ))

43 Example Scheme Function: equalsimp
equalsimp takes two simple lists as parameters; returns #T if the two simple lists are equal; #F otherwise (DEFINE (equalsimp list1 list2) (COND ((NULL? list1) (NULL? list2)) ((NULL? list2) #F) ((EQ? (CAR list1) (CAR list2)) (equalsimp(CDR list1)(CDR list2))) (ELSE #F) ))

44 Example Scheme Function: equal
equal takes two general lists as parameters; returns #T if the two lists are equal; #F otherwise General lists can be atoms or include sublists to any depth (DEFINE (equal list1 list2) (COND ((NOT (LIST? list1))(EQ? list1 list2)) ((NOT (LIST? lis2)) #F) ((NULL? list1) (NULL? list2)) ((NULL? list2) #F) ((equal (CAR list1) (CAR list2)) (equal (CDR list1) (CDR list2))) (ELSE #F) ))

45 Example Scheme Function: append
append takes two lists as parameters; returns the first parameter list with the elements of the second parameter list appended at the end (append ‘(A B) ‘(C D R)) => (A B C D R) (append ‘((A B) C) ‘(D (E F)) => ((A B) C D (E F))

46 Example Scheme Function: append
Define append (DEFINE (append list1 list2) (COND ((NULL? list1) list2) (ELSE (CONS (CAR list1) (append (CDR list1) list2))) ))

47 Example Scheme Function
Try to determine what the guess does. Assume the parameters are simple lists (DEFINE (guess list1 list2) (COND ((NULL? list1) ‘()) ((member (CAR list1) list2) (CONS (CAR list1) (guess (CDR list1) list2))) (ELSE (guess (CDR list1) list2)) ))

48 Example Scheme Function: LET
Recall that LET was discussed in Chapter 5 Is often used to factor out the common subexpressions from more complicated expressions These names can then be used in the evaluation of another expression, but they cannot be rebound to new values in LET LET is actually shorthand for a LAMBDA expression applied to a parameter (LET ((alpha 7))(* 5 alpha)) is the same as: ((LAMBDA (alpha) (* 5 alpha)) 7)

49 The LET Construct Most functional languages include some form of let construct A let construct has two parts The first part binds names to values The second part uses the names defined in the first part In Scheme: (LET ( (name1 expression1) (namen expressionn) )

50 LET Example (DEFINE (quadratic_roots a b c) (LET ( (root_part_over_2a
(/ (SQRT (- (* b b) (* 4 a c)))(* 2 a))) (minus_b_over_2a (/ (- 0 b) (* 2 a))) ) (LIST (+ minus_b_over_2a root_part_over_2a) (- minus_b_over_2a root_part_over_2a)) )) the names bound in the first part of a LET construct cannot be changed in the following expression They could all be eliminated by textual substitution

51 Tail Recursion in Scheme
Definition: A function is tail recursive if its recursive call is the last operation in the function Means that the return value of the recursive call is the return value of the nonrecursive call to the function DEFINE (member atm a_list) (COND ((NULL? a_list) #F) ((EQ? atm (CAR lis)) #T) ((ELSE (member atm (CDR a_list))) ))

52 Tail Recursion in Scheme
A tail recursive function can be automatically converted by a compiler to use iteration, making it faster Scheme language definition requires that Scheme language systems convert all tail recursive functions to use iteration Uses an accumulating parameter and a helper function

53 Tail Recursion in Scheme - continued
Example of rewriting a function to make it tail recursive, using helper a function Original: (DEFINE (factorial n) (IF (<= n 0) 1 (* n (factorial (- n 1))) )) Tail recursive: (DEFINE (facthelper n factpartial) factpartial facthelper((- n 1) (* n factpartial))) (DEFINE (factorial n) (facthelper n 1)) The last operation of factorial

54 Functional Form - Composition
If h is the composition of f and g, h(x) = f(g(x)) (DEFINE (g x) (* 3 x)) (DEFINE (f x) (+ 2 x)) (DEFINE h x) (+ 2 (* 3 x))) (The composition) In Scheme, the functional composition function compose can be written: (DEFINE (compose f g) (LAMBDA (x) (f (g x)))) ((compose CAR CDR) '((a b) c d)) yields c (DEFINE (third a_list) ((compose CAR (compose CDR CDR)) a_list)) is equivalent to CADDR

55 Functional Form – Apply-to-All
Apply to All - one form in Scheme is map Applies the given function to all elements of the given list; (DEFINE (map fun a_list) (COND ((NULL? a_list) '()) (ELSE (CONS (fun (CAR a_list)) (map fun (CDR a_list)))) )) (map (LAMBDA (num) (* num num num)) '( )) yields ( )

56 Functions That Build Code
It is possible in Scheme to define a function that builds Scheme code and requests its interpretation This is possible because the interpreter is a user-available function, EVAL

57 Adding a List of Numbers
((DEFINE (adder a_list) (COND ((NULL? a_list) 0) (ELSE (+ (CAR a_list) (adder (CDR a_list)))) )) (adder ‘(3 4 5))

58 Adding a List of Numbers
((DEFINE (adder a_list) (COND ((NULL? a_list) 0) (ELSE (EVAL (CONS '+ a_list))) )) (adder ‘(3 4 5)) The parameter is a list of numbers to be added; adder inserts a + operator and evaluates the resulting list Use CONS to insert the atom + into the list of numbers. Be sure that + is quoted to prevent evaluation Submit the new list to EVAL for evaluation

59 Support for Functional Programming in Primarily Imperative Languages
Support for functional programming is increasingly creeping into imperative languages Anonymous functions (lambda expressions) JavaScript: leave the name out of a function definition C#: i => (i % 2) == 0 (returns true or false depending on whether the parameter is even or odd) Python: lambda a, b : 2 * a - b

60 Support for Functional Programming in Primarily Imperative Languages (continued)
Python supports the higher-order functions filter and map (often use lambda expressions as their first parameters) map(lambda x : x ** 3, [2, 4, 6, 8]) Returns [8, 64, 216, 512] Python supports partial function applications from operator import add add5 = partial (add, 5) (the first line imports add as a function) Use: add5(15)

61 Support for Functional Programming in Primarily Imperative Languages (continued)
Ruby Blocks Are effectively subprograms that are sent to methods, which makes the method a higher-order subprogram A block can be converted to a subprogram object with lambda times = lambda {|a, b| a * b} Use: x = times.(3, 4) (sets x to 12) Times can be curried with times5 = times.curry.(5) Use: x5 = times5.(3) (sets x5 to 15)

62 Comparing Functional and Imperative Languages
Efficient execution Complex semantics Complex syntax Concurrency is programmer designed Functional Languages: Simple semantics Simple syntax Less efficient execution Programs can automatically be made concurrent

63 Report & presentation #1: Survey on support for object-oriented programming & functional programming of Swift, Scalar and Haskell, and compare them #2: Solve & Execute these problems in Scheme. Programming Exercises 6~9


Download ppt "Chapter 15 Functional Programming Languages"

Similar presentations


Ads by Google