1 cosc3306: programming paradigms lecture 10: applicative programming specifications haibin zhu,...
TRANSCRIPT
11
COSC3306:COSC3306:Programming ParadigmsProgramming Paradigms
Lecture 10: ApplicativeLecture 10: ApplicativeProgramming SpecificationsProgramming Specifications
Haibin Zhu, Ph.D.Haibin Zhu, Ph.D.Computer ScienceComputer ScienceNipissing University Nipissing University
(C) 2003(C) 2003
22
The Lambda CalculusThe Lambda Calculus
EverythingEverything is a function. is a function. – There are no other types---no integers, strings, lists, There are no other types---no integers, strings, lists,
booleans, etc. There is no unit (). If you want these booleans, etc. There is no unit (). If you want these things, you must encode them using functions. Luckily, things, you must encode them using functions. Luckily, functions are powerful enough to do this. functions are powerful enough to do this.
No state or side effects. No state or side effects. – It is purely functional. Thus we can think exclusively in It is purely functional. Thus we can think exclusively in
terms of the substitution model. terms of the substitution model.
The order of evaluation is irrelevant. The order of evaluation is irrelevant. – The lambda calculus does not specify an evaluation The lambda calculus does not specify an evaluation
order. order.
Only unary (one-argument) functions. Only unary (one-argument) functions. – Functions of multiple arguments are encoded by Functions of multiple arguments are encoded by
currying.currying.
33
Key properties of functional Key properties of functional programming programming
Lazy function evaluationLazy function evaluation, which is a mechanism that , which is a mechanism that eliminates unnecessary evaluation of functions and eliminates unnecessary evaluation of functions and includes two strategies:includes two strategies:– Postponing evaluation of a function until it is needed, andPostponing evaluation of a function until it is needed, and– Eliminating the reevaluation of the same function more than once.Eliminating the reevaluation of the same function more than once.
First-class objectsFirst-class objects, which means that functions are , which means that functions are treated like any other object in the language. treated like any other object in the language. All programs and procedures are functionsAll programs and procedures are functions, which , which clearly distinguishes incoming values as parameter values clearly distinguishes incoming values as parameter values from outgoing values as evaluation results.from outgoing values as evaluation results.Lack of variable and assignmentLack of variable and assignment, which eliminates the , which eliminates the concept of variable, except as a name for a value, and concept of variable, except as a name for a value, and assignment as an available operation. assignment as an available operation.
44
Key properties (2)Key properties (2)Lack of loop and iterationLack of loop and iteration, which means that there is no , which means that there is no loop and that loops are replaced by recursive calls. loop and that loops are replaced by recursive calls. Referential transparencyReferential transparency,, which is the property of a function which is the property of a function whereby its value depends only on the values of its whereby its value depends only on the values of its parameters, not on any previous computations, the order of parameters, not on any previous computations, the order of evaluation, or the execution path that led to the call. . evaluation, or the execution path that led to the call. . Dynamic Memory EnvironmentDynamic Memory Environment, which is allocation and , which is allocation and deallocation of memory during program execution. As a deallocation of memory during program execution. As a consequence, a fully dynamic environment must perform consequence, a fully dynamic environment must perform some kind of automatic reclamation of unreachable storage. some kind of automatic reclamation of unreachable storage. Automatic memory management actually falls into two Automatic memory management actually falls into two categories: categories: – Reclamation of Storage, Reclamation of Storage, which is the process of reclaming which is the process of reclaming
previously allocated but no longer used storage, sometimes called previously allocated but no longer used storage, sometimes called garbage collectiongarbage collection, as we discussed in Chapter 3., as we discussed in Chapter 3.
– Maintaining Free SpaceMaintaining Free Space, which is the process of maintaining the free , which is the process of maintaining the free space available for allocation, as we discussed in Chapter 3.space available for allocation, as we discussed in Chapter 3.
55
Key properties (3)Key properties (3)
Garbage CollectionGarbage Collection, which is the process of , which is the process of keeping track of inaccessible storage and keeping track of inaccessible storage and permitting it to be reallocated.permitting it to be reallocated.
Side-effect freedomSide-effect freedom, which is the ability to call , which is the ability to call a function without producing side effects, that is, a function without producing side effects, that is, without changing the internal state of the without changing the internal state of the computations. Side effects are operations that computations. Side effects are operations that permanently change the value of a variable or permanently change the value of a variable or other observable objects. other observable objects.
66
Lambda CalculusLambda Calculus
A mathematical method for expressing computation by A mathematical method for expressing computation by functions and is used for studying functional functions and is used for studying functional programming language concepts. programming language concepts. Lambda calculus gets its name from the Greek letter Lambda calculus gets its name from the Greek letter lambda, lambda, . . The general form of a lambda expression, known as the The general form of a lambda expression, known as the lambda function, islambda function, is idid1, 1, idid2, …, 2, …, idnidn. . expressionexpression
where the where the idid’s are identifiers (parameters or variables) ’s are identifiers (parameters or variables) and and expressionexpression (called the body of the lambda function) (called the body of the lambda function) is some expression that may involve the identifiers. is some expression that may involve the identifiers.
77
An exampleAn example
xx. . xxxx– is a function that maps any value of is a function that maps any value of xx to to xxxx and and
defines a mapping from an integer number to integer defines a mapping from an integer number to integer numbers, yielding the square of integer numbers. This numbers, yielding the square of integer numbers. This lambda expression can be applied aslambda expression can be applied as
{{xx. . xxxx }(2) }(2)– where the result of the lambda expression where the result of the lambda expression xxxx can be can be
deduced by replacing the parameter and evaluating deduced by replacing the parameter and evaluating the resulting expression with 2. the resulting expression with 2.
88
Figure 12.1 A lambda expression with evaluation value
© 2003 Brooks/Cole Publishing / Thomson Learning™
99
Lambda notationLambda notation
Lambda notation allows the definition of a function Lambda notation allows the definition of a function without a name. without a name. – For example, For example, xx. . xxxx defines a lambda function that defines a lambda function that
maps each maps each xx in the integer domain to in the integer domain to xx22. .
Generally speaking, the value of a lambda Generally speaking, the value of a lambda expression such asexpression such as
idid1, 1, idid2, …, 2, …, idnidn. . expressionexpression ( (aa1, 1, aa2, …, 2, …, anan))when applied to arguments (when applied to arguments (aa1, 1, aa2, …, 2, …, anan), is ), is given by evaluating given by evaluating expressionexpression, with , with a1a1 substituted for all occurrences of substituted for all occurrences of idid1, 1, aa2 2 substituted for all occurrences of substituted for all occurrences of idid2, and 2, and anan substituted for all occurrences of substituted for all occurrences of idnidn. .
1010
Figure 12.2 Examples of lambda funcions
1111
More examplesMore examples
{{xx. (. ( xx xx)}()}( 3 4) 3 4) { {xx. (. ( xx xx)}(7) )}(7) ( ( 7 7) 7 7) 1414
{{xx. (. ( xx xx)}()}( 3 4) 3 4) { { ( ( 3 4)} ( 3 4)} ( 3 4)} 3 4)} { { 7 7 7} 7} 14 14
In the following example, we use two arguments In the following example, we use two arguments with the abstraction to define a function, with the abstraction to define a function, replacing replacing ff with sqr, a predefined square with sqr, a predefined square function, and function, and xx with 3. with 3.
{{{{{{ff. {. {xx. (. (ff ( (ff xx))}}sqr}3} ))}}sqr}3} {{ {{xx. (sqr(sqr . (sqr(sqr xx))}3} ))}3}
(sqr(sqr 3)) (sqr(sqr 3)) (sqr 9) (sqr 9) 81 81
1212
Function definitionsFunction definitions
Lambda FunctionLambda Function Function NameFunction Name
xx, , yy. . xx yy PlusPlus
xx. . x x xx SquareSquare
xx. . x x 1 1 SuccessorSuccessor
xx. . x x 1 1 PredecessorPredecessor
xx, , yy. if . if xx yy, then , then xx else else yy end end MaxMax
xx. . xx IdentityIdentity
1313
AmbiguityAmbiguity
The lambda expression The lambda expression xx. . yy. . f f ((gg))
admits three possible interpretations, admits three possible interpretations, illustrating the ambiguity of the lambda illustrating the ambiguity of the lambda calculus grammar:calculus grammar: xx. {. {yy. {. {f f ((gg)}},)}}, xx. {{. {{yy. . ff } ( } (gg)}, and)}, and– {{xx. . yy. . ff } ( } (gg).).
1414
Remove ambiguityRemove ambiguity
Complicating the grammar and Using Complicating the grammar and Using parentheses. parentheses.
However, it is preferable to leave the grammar However, it is preferable to leave the grammar as it is and add the convention that the function as it is and add the convention that the function application has the highest precedence. application has the highest precedence.
Thus, by default, the interpretation of the Thus, by default, the interpretation of the preceding expression is the first entry in the list. preceding expression is the first entry in the list.
Braces are used to override this precedence Braces are used to override this precedence when necessary. when necessary.
1515
Free and Bound IdentifiersFree and Bound Identifiers
xx. . x+yx+y– Y is a reference that is not bounded called a Y is a reference that is not bounded called a
free identifier.free identifier.
xx. . x+y (5)=5+yx+y (5)=5+y
x, y, zx, y, z. . x+y+z => {x+y+z => {x. {x. {y. {y. {zz. (. (x+y+z)}}}x+y+z)}}}
Free identifiers may be renamed without Free identifiers may be renamed without changing the value of expressions within changing the value of expressions within which they occur.which they occur.
1616
Figure 12.3 A lambda expression with free and bound identifiers
© 2003 Brooks/Cole Publishing / Thomson Learning™
1717
ReductionsReductions
Alpha-conversion (Alpha-conversion (αα-conversion)-conversion) xx. . E αα y. E[ x → y]
(( w. ( w. ( y. y. z) w) z) w) αα (( x. ( x. ( y. y. z) x) z) x)
Beta-conversion(Beta-conversion(ββ-conversion)-conversion) x. x. E1 E2 ββ E1 [x → E2]
((x. x +1) 5 x. x +1) 5 ββ 5+1 6 6
((g. g (g. g (a. a. b. a)) ((b. a)) ((a. a. b. b. f. f a b) p q)f. f a b) p q)
ββ ((((a. a. b. b. f. f a b) p q) (f. f a b) p q) (a. a. b. a)b. a)
ββ ((b. b. f. f p b) q) (f. f p b) q) (a. a. b. a)b. a)
ββ ((f. f p q) (f. f p q) (a. a. b. a)b. a)
ββ ((a. a. b. a) (p q) b. a) (p q) ββ ( ( b. p) (q) b. p) (q) ββ p p
1818
Reductions (2)Reductions (2)
Eta-conversion(Eta-conversion(ηη-conversion)-conversion)– {{x. x. E} x x ηη E
{{x. x. (sqr 5)} x x ηη (sqr 5) ηη 25
{{x. x. y} x x ηη y
Gamma-conversion(Gamma-conversion(δδ-conversion)-conversion)– {function x y} {function x y} δδ function (x y)
Add 5 3 δδ add(5 3) 8
P407 examplesP407 examples
1919
The Church-Rosser TheoremThe Church-Rosser Theorem
If a lambda expression M evaluates to a normal If a lambda expression M evaluates to a normal form A via a sequence of reduction (M form A via a sequence of reduction (M *A), and *A), and another sequence of reductions takes M to a another sequence of reductions takes M to a normal form B (normal form B (M M *B), then some common *B), then some common term N can be found such that A can be reduced term N can be found such that A can be reduced to N (to N (A A *N and *N and B B *N).*N).
Any relation that satisfies this condition is said to Any relation that satisfies this condition is said to have the diamond property or the confluence have the diamond property or the confluence property.property.
2020
Figure 12.4 The Church-Rosser theorem
© 2003 Brooks/Cole Publishing / Thomson Learning™
2121
Figure 12.5 Alternative evaluations of a lambda expression
© 2003 Brooks/Cole Publishing / Thomson Learning™
2222
Order of evaluationOrder of evaluation
No two orders of evaluation of a lambda No two orders of evaluation of a lambda expression can give different normal expression can give different normal forms.forms.Normal order (call-by-name)Normal order (call-by-name)– Reduce the left most expression at every Reduce the left most expression at every
stage.stage.
Applicative order (call-by-value)Applicative order (call-by-value)– Evaluates the function and the argument of an Evaluates the function and the argument of an
application first.application first.
2323
An exampleAn example
Normal order:Normal order:– ((x. x + x + x + xx. x + x + x + x) ((x. x. x) a)– (x. x. x) a + (x. x. x) a+ (x. x. x) a+ (x. x. x) a– a + (x. x. x) a+ (x. x. x) a+ (x. x. x) a– a + a+ (x. x. x) a+ (x. x. x) a– a + a+ a+ (x. x. x) a– a + a+ a+ a
Applicative order– ((x. x + x + x + xx. x + x + x + x) ((x. x. x) a)– ((x. x + x + x + xx. x + x + x + x) (a)– a + a+ a+ a
2424
To be continued To be continued
Principles of Functional ProgrammingPrinciples of Functional Programming
2525
Principles of Functional Principles of Functional ProgrammingProgramming
A relation describes associations between A relation describes associations between objects.objects.
For example, consider two set of elements, For example, consider two set of elements, XX and and YY. A relation . A relation RR between between XX and and YY is is defined as a set of pairs of elements such as defined as a set of pairs of elements such as {{aa1, 1, bb11,,aa2 2 bb22, … ,, … ,anan, , bnbn}, where }, where every every ai ai is a member of is a member of XX and every and every bibi is a is a member of member of YY. Here, . Here, XX is called the source is called the source domain, and domain, and YY is called the target domain. is called the target domain.
2626
Figure 12.6 A relation expressing {<x1, y1>, <x1, y2>, <x2, y2>, <x4, y3>, <x4, y5>}
© 2003 Brooks/Cole Publishing / Thomson Learning™
2727Figure 12.7 A function expressing {<x1, y1>, <x2, y2>, <x3, y4>, <x4, y5>}
© 2003 Brooks/Cole Publishing / Thomson Learning™
A relation such that there is A relation such that there is at most oneat most one such such yy for for every every xx is said to be a function that corresponds to a is said to be a function that corresponds to a mapping from one element of mapping from one element of XX to one element of to one element of YY..
2828
FunctionsFunctions
A function can be defined in terms of four A function can be defined in terms of four components:components:– AA domain set domain set, which is the set of objects to which the , which is the set of objects to which the
function can be applied;function can be applied;– AA range set range set, which is the set containing all objects , which is the set containing all objects
that can result from an application of the function;that can result from an application of the function;– AA definition definition, which is the specification of how a range , which is the specification of how a range
element is determined from a domain element; andelement is determined from a domain element; and– AA name name, which is a symbol dedicated to the function., which is a symbol dedicated to the function.
2929
Functions (2)Functions (2)
A function can be viewed as a set of pairs A function can be viewed as a set of pairs (x, y) such that y(x, y) such that yF(x) or as a subset of F(x) or as a subset of the Cartesian Product Xthe Cartesian Product XY:Y:
F F { (x, y) { (x, y) X XY | yY | yF(x) }F(x) }where where means “is equivalent to” and means “is equivalent to” and means “is contained in”. This is an means “is contained in”. This is an advantage of viewing a function as a set advantage of viewing a function as a set for the study of the definition of functions for the study of the definition of functions in programming languages.in programming languages.
3030
An exampleAn example
F(x) F(x) (x (x1) Mod 101) Mod 10
Indicating that, the function on the set of digits Indicating that, the function on the set of digits (i.e., {0,1,2,3,4,5,6,7,8,9}) adds one to each digit (i.e., {0,1,2,3,4,5,6,7,8,9}) adds one to each digit in modulo fashion This function can be in modulo fashion This function can be represented as the following set of pairs:represented as the following set of pairs:
{(0,1),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),{(0,1),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9),(9,0)}(8,9),(9,0)}
or in set terminology as:or in set terminology as:
F F { (x, y) { (x, y) digit digitdigit | ydigit | y (x (x1) Mod 1) Mod 10}10}
3131
An alternative representationAn alternative representation
A function isA function is– F F ( (xx1, 1, xx2, … , 2, … , xnxn, value, value))
where the last argument is called the where the last argument is called the function resultfunction result and uniquely can be and uniquely can be determined by the argument values of determined by the argument values of xx1, 1, xx2, … , 2, … , xnxn. .
3232
Six independent components of FP Six independent components of FP
Set of primitivesSet of primitives, which are predefined by the , which are predefined by the language as the basic functions and language as the basic functions and correspond to the built-in operations of correspond to the built-in operations of imperative languages. imperative languages. Set of functional formsSet of functional forms, which are functions , which are functions that accept functions as parameters to create that accept functions as parameters to create new functions. new functions. Application operationApplication operation, which is the built-in , which is the built-in mechanism for applying a function to its mechanism for applying a function to its arguments and producing a value as the result. arguments and producing a value as the result.
3333
Six independent components (2)Six independent components (2)
Set of data objectsSet of data objects, which are the allowed members of , which are the allowed members of the domain and range sets. Data objects consist of some the domain and range sets. Data objects consist of some atomic type and the ability to construct some form of atomic type and the ability to construct some form of aggregate objects from other objects.aggregate objects from other objects.Binding names to functionsBinding names to functions, which is a mechanism for , which is a mechanism for denoting names to the new functions being defined. denoting names to the new functions being defined. Dynamic storage managementDynamic storage management, which is an implicit , which is an implicit storage allocation and a garbage collection mechanism storage allocation and a garbage collection mechanism because the functional languages do not provide because the functional languages do not provide facilities for directly modifying the state of the storage for facilities for directly modifying the state of the storage for a computation. a computation.
3434
Orders of FunctionsOrders of Functions
A function whose parameters and result A function whose parameters and result are all nonfunctional is called a are all nonfunctional is called a first-orderfirst-order functionfunction. .
A function that has a functional parameter A function that has a functional parameter or result is called a or result is called a higher orderhigher order functionfunction. .
3535
Essential primitivesEssential primitives
Selection operations:Selection operations: FIRST is used to extract FIRST is used to extract the first element of a sequence of elements, the first element of a sequence of elements, LAST is used to extract the last element, and LAST is used to extract the last element, and TAIL is used to extract all the elements but the TAIL is used to extract all the elements but the first element. first element. – x1x1 FIRST: FIRST: x1,x2, … ,xnx1,x2, … ,xn– xnxn LAST: LAST: x1,x2, … ,xnx1,x2, … ,xn x2, … ,xnx2, … ,xn TAIL: TAIL: x1,x2, … ,xnx1,x2, … ,xnExamplesExamples– first: first: 3,2,4,63,2,4,6 3 3– last: last: 3,2,4,63,2,4,6 6 6– tail: tail: 3,2,4,63,2,4,6 2,4,62,4,6
3636
Essential primitives (2)Essential primitives (2)
Structuring operations:Structuring operations: Operations are used to combine, Operations are used to combine, dissect, or rearrange elements. dissect, or rearrange elements. xn,x1, … ,xn-1xn,x1, … ,xn-1 ROTR: ROTR: x1,x2, … ,xnx1,x2, … ,xn (ROTate (ROTate
Right)Right) x2, … ,xn,x1x2, … ,xn,x1 ROTL: ROTL: x1,x2, … ,xnx1,x2, … ,xn (ROTate Left)(ROTate Left)– nn LENGTH: LENGTH: x1,x2, … ,xnx1,x2, … ,xn (LENGTH)(LENGTH) x,x1,x2, … ,xnx,x1,x2, … ,xn CONS: CONS: x,x,x1,x2, … ,xnx1,x2, … ,xn – (CONstruct Sequence)(CONstruct Sequence)
For example,For example,– rotr: rotr: 3,2,4,63,2,4,6 6,3,2,46,3,2,4– rotl: rotl: 3,2,4,63,2,4,6 2,4,6,32,4,6,3– length: length: 3,2,4,63,2,4,6 4 4– cons: cons: 3,3,2,4,62,4,6 3,2,4,63,2,4,6
3737
Essential primitives (3)Essential primitives (3)
Arithmetic operations:Arithmetic operations: Ordinary arithmetic operations Ordinary arithmetic operations are applied to sequences of two elements to produce a are applied to sequences of two elements to produce a new element; + is used for addition, new element; + is used for addition, for subtraction, * for subtraction, * for multiplication, for multiplication, for division and, | for residue for division and, | for residue operation. In functional arithmetic operations we use the operation. In functional arithmetic operations we use the prefix form (e.g., prefix form (e.g., ::x,yx,y instead of the usual Infix instead of the usual Infix notation (e.g., notation (e.g., xx yy). The following are some function ). The following are some function definitions.definitions.: : x,yx,y x xyy : : 3,23,2 5 5: : x,yx,y x xyy : : 8,28,2 4 4: : x,yx,y x xyy : : 3,23,2 6 6: : x,yx,y x xyy : : 6,36,3 3 3|: |: x,yx,y x x(x(xy)y)yy |: |: 9,29,2 1 1
3838
Essential primitives (4)Essential primitives (4)Predicate operations:Predicate operations: Operations are used to produce Operations are used to produce results as truth values. We represent truth by T and false by results as truth values. We represent truth by T and false by F in which a predicate function yields either T or F. In F in which a predicate function yields either T or F. In addition to predicates for comparing numbers such as addition to predicates for comparing numbers such as , , , , , , , and , and , it provides predicates to inquire about , it provides predicates to inquire about sequences and atoms. For example, in the following two sequences and atoms. For example, in the following two examples, the first returns a Boolean (T or F) from an inquiry examples, the first returns a Boolean (T or F) from an inquiry of an atom object, whereas the second returns a Boolean (T of an atom object, whereas the second returns a Boolean (T or F) from an inquiry of a sentence.or F) from an inquiry of a sentence.ATOM:x ATOM:x if x is an atom then T else F if x is an atom then T else F
atom: atom: a,ba,b F FNULL:x NULL:x if x if x nil then T else F nil then T else F
null: null: a,ba,b F Feq: eq: a,ba,b F Feq: eq: a,aa,a T T: : 4,24,2 T T
3939
Essential primitives (5)Essential primitives (5)
Logical operations:Logical operations: Operations provide the Operations provide the combination of the truth values. The operators are AND, combination of the truth values. The operators are AND, OR, and NOT. OR, and NOT. AND: AND: x,yx,y T if both are T T if both are T
and: and: T,FT,F F Fand: and: T,TT,T T T
OR: OR: x,yx,y T if one is T T if one is Tor: or: T,FT,F T Tor: or: F,FF,F F F
NOT: NOT: xx T if x is F T if x is Fnot: not: TT F Fnot: not: FF T T
4040
Essential primitives (5)Essential primitives (5)
Identity operation:Identity operation: The function ID yields The function ID yields the same element. For example,the same element. For example,
x x ID:x ID:x
id:a id:a a a
The most interesting features of FP The most interesting features of FP languages are their functional forms languages are their functional forms because we are not used to functional forms because we are not used to functional forms in conventional programming languages. in conventional programming languages.
4141
Program-Forming Operations Program-Forming Operations (PFO)(PFO)
CompositionComposition
ConstructionConstruction
InsertInsert
Apply to allApply to all
ConditionCondition
4242
CompositionComposition
The functional form The functional form compositioncomposition, denoted , denoted °°, has the , has the syntaxsyntax((f f °°gg): ): XX ff : ( : ( gg : : XX))takes two functions as the arguments, and produces a takes two functions as the arguments, and produces a function equivalent to the application of the first function equivalent to the application of the first argument to the result of the application of the second argument to the result of the application of the second argument. For example, if we define two functions asargument. For example, if we define two functions as
ff((xx) ) xx 5 and 5 and gg((xx) ) xx 4 4then one composition form of then one composition form of ff and and gg can be obtained: can be obtained: hh((xx) ) ff((gg((xx)), or )), or
hh((xx) ) ( (xx 4) 4) 5 5 xx 9 9
4343
An exampleAn example
The composition of the rotate left and The composition of the rotate left and construct sequence operations applied to construct sequence operations applied to a list of elements.a list of elements.
ROTLROTL°°CONS: CONS: x1, x1, x2,x3,x4x2,x3,x4
ROTL: CONS: ROTL: CONS: x1,x1,x2,x3,x4x2,x3,x4
ROTL: ROTL: x1,x2,x3 ,x4x1,x2,x3 ,x4 x2,x3,x4,x1x2,x3,x4,x1
4444
ConstructionConstruction
The functional form The functional form constructionconstruction, denoted [ ], has the , denoted [ ], has the syntaxsyntax– [ [ ff1, 1, ff2, … , 2, … , fnfn ] : ] : XX f f1 : 1 : XX, , ff2 : 2 : XX, … , , … , fnfn : : XX
where it takes as arguments where it takes as arguments nn functions, and yields a functions, and yields a function equivalent to applying each of the functions to function equivalent to applying each of the functions to the same argument and forming a sequence of the the same argument and forming a sequence of the results. For example, if we have individual functions for results. For example, if we have individual functions for the the maximummaximum, , minimumminimum, and , and averageaverage of a sequence of of a sequence of numbers, we define a construction as:numbers, we define a construction as:– [Maximum, Minimum, Average][Maximum, Minimum, Average]
Then, for example, Then, for example, 5, 1, 35, 1, 3 is the produced result of is the produced result of– [Maximum, Minimum, Average]:[Maximum, Minimum, Average]:1,2,3,4,51,2,3,4,5
4545
InsertInsert
The functional form The functional form insertinsert, denoted , denoted , has the following , has the following syntaxsyntax ff : : XX1, 1, XX2, … , 2, … , XnXn ff : : X X1, 1, ff : : XX2, … , 2, … , XnXn takes a function as an argument and yields a function takes a function as an argument and yields a function equivalent to applying the argument function to equivalent to applying the argument function to successive elements of the sequence. For example,successive elements of the sequence. For example, ff : : if x is if x is X1X1, then X1, then X1
else if x is the sequence else if x is the sequence X1, X2, … , Xn X1, X2, … , Xn and and nn22
then then ff: : X1, X1, ff: : X2, … , Xn X2, … , Xn
4646
An exampleAn example
Thus Thus +:+: 1,2,3,4,5 1,2,3,4,5 yields 15 as illustrated in yields 15 as illustrated in the following.the following.+:+:1,2,3,4,51,2,3,4,5 +: +:1, 1, +:+:2,3,4,52,3,4,5 +:+:1, +:1, +:2, 2, +:+:3,4,53,4,5 +:+:1, +:1, +:2, +:2, +:3, 3, +:+:4,54,5 +:+:1, +:1, +:2, +:2, +:3, +:3, +:4, 4, +:+:55 +:+:1, +:1, +:2, +:2, +:3, +:3, +:4, 54, 5 +:+:1, +:1, +:2, +:2, +:3, 93, 9+:+:1, +:1, +:2, 122, 12 +: +:1, 141, 14 15 15
4747
Apply to AllApply to All
The functional form The functional form apply_to_allapply_to_all, denoted , denoted , has , has the syntaxthe syntax
ff: : XX1, 1, XX2, …, 2, …, XnXn f f : : XX1, 1, ff : : XX2, … , 2, … , ff : : XnXn This function can be illustrated in the following way.This function can be illustrated in the following way.
ff: : if x is nil, then nilif x is nil, then nil
else if x is the sequence else if x is the sequence X1, X2, …, X1, X2, …, XnXn
then then ff:X1, :X1, ff:X2, …, :X2, …, ff:Xn:Xn
4848
An exampleAn example
This form takes a function as an argument and This form takes a function as an argument and yields a function equivalent to applying the yields a function equivalent to applying the argument function to each element of the argument function to each element of the sequence and forming a sequence of the results. sequence and forming a sequence of the results. For example, For example,
::2,32,3,,4,54,5,,6,26,2
yields yields 5,9,85,9,8, as illustrated in the following., as illustrated in the following.
::2,32,3,,4,54,5,,6,26,2 ::2,32,3,,::4,54,5,,::6,26,2 5,9,85,9,8
4949
ConditionCondition
The functional form condition, denoted IF, takes The functional form condition, denoted IF, takes three functions as arguments and, depending on three functions as arguments and, depending on the evaluation result of the first function as True the evaluation result of the first function as True or False, returns the second or third function, or False, returns the second or third function, respectively. This function has the syntaxrespectively. This function has the syntax(IF function1 function2 function3):x (IF function1 function2 function3):x if function1:xif function1:xT T thenthen function2:xfunction2:x elseelsefunction3:xfunction3:x if function1=x if function1=x thenthen function2function2 elseelsefunction3function3
5050
ExamplesExamples
In the following two examples, evaluation of the In the following two examples, evaluation of the head of head of 2,3,52,3,5 with 2 and 3 yields the tail and with 2 and 3 yields the tail and last element of the list, respectively.last element of the list, respectively.– (IF FIRST:(IF FIRST:2,3,52,3,5 TAIL: TAIL:2,3,52,3,5 LAST: LAST:2,3,52,3,5):2):2 (IF 2 (IF 2 3,53,5 5):2 5):2 3,53,5– (IF FIRST:(IF FIRST:2,3,52,3,5 TAIL: TAIL:2,3,52,3,5 LAST: LAST:2,3,52,3,5):3):3 (IF 2 (IF 2 3,53,5 5):3 5):3 55
5151
Lisp PlatformLisp Platform
http://www.lispworks.com/downloads/http://www.lispworks.com/downloads/index.htmlindex.html
5252
SummarySummary
Lambda CalculusLambda Calculus– PropertiesProperties– AmbiguityAmbiguity– reductionsreductions
Principles of FPPrinciples of FP– Components of a functionComponents of a function– Components of FPLComponents of FPL– PFOPFO
•http://www.cs.cornell.edu/Courses/cs312/2001FA/lecture/lec25.htmhttp://www.cs.uiowa.edu/~slonnegr/plf/Book/Chapter5.pdf