<<

Topics

Introduction Chapter 15 Functional programs Mathematical functions Functional forms Eager and lazy evaluation Haskell

Chapter 15: Functional Programming 2

Introduction Functional Programs

Emerged in the early 1960s for Artificial A program is a description of a specific Intelligence and its subfields: computations.

n Theorem proving n A program can be seen as a “black box” for obtaining outputs from inputs. n Symbolic computation n From this point of view, a program is n Rule-based systems equivalent to a mathematical . n Natural language processing The original functional language was Lisp, developed by John McCarthy (1960)

Chapter 15: Functional Programming 3 Chapter 15: Functional Programming 4

Mathematical Functions Mathematical Functions

A function is a rule that associates to each n The x in f(x), which represents any value from x from some set X of values a unique y X (domain), is called independent variable. from another set Y of values. n The y from the set Y (range), defined by the equation y = f(x) is called dependent variable. n In mathematical terminology, if f is the name of the function n Sometimes f is not defined for all x in X, it is y = f(X) or called a partial function. Otherwise it is a total f: X à Y function.

n The set X is called the domain of f. Example: square(x) = x * x mapping n The set Y is called the range of f. function expressions parameters name Chapter 15: Functional Programming 5 Chapter 15: Functional Programming 6

1 Mathematical Functions: Mathematical Functions variables Everything is represented as a mathematical In imperative programming languages, function: variables refer to memory locations as well n Program: x represents the input and y as values. represents the output. x = x + 1 n Procedure or function: x represents the parameters and y represents the returned n Means “update the program state by adding 1 to the values. value stored in the memory cell named x and then No distinction between a program, a storing that sum back into that memory cell” n The name x is used to denote both a value (as in x+1), procedure, and a function. However, there is often called an -value, and a memory address, called a clear distinction between input an output an l-value. values. Chapter 15: Functional Programming 7 Chapter 15: Functional Programming 8

Mathematical Functions: Mathematical Functions: variables variables Consequences of the lack of variables In , variables always stand for and assignment actual values, there is no concept of 1. No loops. memory location (l-values of variables). n The effect of a loop is modeled via recursion, n Eliminates the concept of variable, except as since there is no way to increment or decrement a name for a value. the value of variables. 2. No notation of the internal state of a function. n Eliminates assignment as an available operation. l The value of any function depends only on the values of its parameters, and not on any previous computations, including calls to the function itself.

Chapter 15: Functional Programming 9 Chapter 15: Functional Programming 10

Mathematical Functions: Mathematical Functions variables

l The value of a function does not depend on the Functional Forms order of evaluation of its parameters. l The property of a function that its value depend n Def: A higher-order function, or functional only on the values of its parameters is called form, is one that either takes functions as . parameters or yields a function as its result,

3. No state. or both n There is no concept of memory locations with changing values. n Names are associated to values which once the value is set it never changes.

Chapter 15: Functional Programming 11 Chapter 15: Functional Programming 12

2 Functional Forms Functional Forms

1. Function Composition 2. Construction

n A functional form that takes two functions as n A functional form that takes a list of parameters and yields a function whose value functions as parameters and yields a list of is the first actual parameter function applied to the results of applying each of its parameter the application of the second functions to a given parameter Form: h º f ° g Form: [f, g] which means h (x) º f ( g ( x )) For f (x) º x * x * x and For f (x) º x * x * x and g (x) º x + 3, g (x) º x + 3, [f, g] (4) yields (64, 7) h º f ° g yields (x + 3)* (x + 3)* (x + 3)

Chapter 15: Functional Programming 13 Chapter 15: Functional Programming 14

Functional Forms Pure Functional Programming

3. Apply-to-all In pure functional programming there are

n A functional form that takes a single function no variables, only constants, parameters, as a parameter and yields a list of values and values. obtained by applying the given function to Most functional programming languages each element of a list of parameters retain some notation of variables and Form: a assignment, and so are “impure”

For h (x) º x * x * x n It is still possible to program effectively using a( h, (3, 2, 4)) yields (27, 8, 64) the pure approach.

Chapter 15: Functional Programming 15 Chapter 15: Functional Programming 16

Lambda Calculus Lambda Calculus

The foundation of functional programming Application of a lambda expression to a developed by Church (1941). value: ((lx×x*x)2) which evaluates to 4 A lambda expression specifies the parameters What is a lambda expression? and definition of a function, but not its name. 1. Any identifier is a lambda expression. 2. If M and N are lambda expressions, then the n Example: lambda expression that defined the application of M to N, written (MN) is a lambda function square: expression. (lx×x*x) 3. An abstraction, written (lx×M) where x is an n The identifier x is a parameter for the (unnamed) identifier and M is a lambda expression, is also function body x*x. a lambda expression.

Chapter 15: Functional Programming 17 Chapter 15: Functional Programming 18

3 Lambda Expressions: free and Lambda Expressions: BNF bound variables A simple BNF grammar for the syntax of In the lambda expression (lx×M) the lambda calculus n The identifier x is said to be bound in the LambdaExpression à ident | (M N) | (l ident × M) subexpression M. M à LambdaExpression n Any identifier not bound in M is said to be free. à N LambdaExpression n Free variables are like globals and bound Examples: variables are like locals. n Free variables can be defined as: x free(x) = x l × ( x x) free(MN) = free(M) È free(N) ((lx×x)(ly×y)) free(lx×M) = free(M) – {x}

Chapter 15: Functional Programming 19 Chapter 15: Functional Programming 20

Lambda Expressions: Lambda Expressions: substitution substitution

A substitution of an expression N for a variable Examples: x in M, written M[N/x], is defined: x[y/x] = y 1. If the free variable of N have no bound occurrences in M, then the term M[N/x] is formed by replacing all (xx)[y/x] = (yy) free occurrences of x in M by N. (zw)[y/x] = (zw)

2. Otherwise, assume that the variable y is free in N (zx)[y/x] = (zy) and bound in M. Then consistently replace the [lx×(zx))[y/x] = (lu×(zu))[y/x] = (lu×(zu)) binding and corresponding bound occurrences of y in M by a new variable, say u. Repeat this renaming of bound variables in M until the condition in Step 1 applies, then proceed as in Step 1.

Chapter 15: Functional Programming 21 Chapter 15: Functional Programming 22

Lambda Expressions: beta- Functional Programming vs. reduction Lambda Calculus The meaning of a lambda expression is A functional programming languages is defined by the beta-reduction rule: essentially an applied lambda calculus ((lx×M)N) Þ M[N/x] with constant values and functions build in. An evaluation of a lambda expression is a n The pure lambda expression (xx) can be sequence P Þ Q Þ R Þ … written as (x times x) or (x*x) or (* x x)

n Each expression in the sequence is obtained by n When constants, such as numbers, are added the application of a beta-reduction to the (with their usual interpretation and definitions previous expression. for functions, such as *), then applied lambda ((ly×((lx×xyz)a))b) Þ ((ly×ayz)b) Þ (abz) calculi is obtained

Chapter 15: Functional Programming 23 Chapter 15: Functional Programming 24

4 Eager Evaluation

An important distinction in functional languages is usually made in the way they (if ( = x 0 ) 1 ( / 1 x )) define function evaluation.

Eager Evaluation or call by value: In n Defined the value of the function to be 1 when languages such as Scheme, all arguments x is zero and 1/x otherwise. to a function are normally evaluated at the n If all arguments to the if functions are time of the call. evaluated at the time of the call, division by n Functions such as if and and cannot be zero cannot be prevented. defined without potential run-time error

Chapter 15: Functional Programming 25 Chapter 15: Functional Programming 26

Lazy Evaluation Eager vs. Lazy Evaluation

An advantage of eager evaluation is An alternative to the eager evaluation efficiency in that each argument passed to strategy is lazy evaluation or call by name, a function is only evaluated once, in which an argument to a function is not n In lazy evaluation, an argument to a function evaluated (it is deferred) until it is needed. is reevaluated each time it is used, which can be more than once. n It is the default mechanism of Haskell. An advantage of lazy evaluation is that it permits certain interesting functions to be defined that cannot be implemented as eager languages

Chapter 15: Functional Programming 27 Chapter 15: Functional Programming 28

Haskell

The interactive use of a functional language is provided by the HUGS (Haskell Users Gofer System) environment developed by Mark Jones Haskell of Nottingham University. HUGS is available from http://www.haskell.org/hugs/ The Haskell web page is http://www.haskell.org/

Chapter 15: Functional Programming 30

5 Haskell: sessions Haskell: scripts

Expressions can be typed directly into the Scripts are collections of definitions supplied Hugs/Haskell screen. by the programmer. n The computer will respond by displaying the à result of evaluating the expression, followed square :: Integer Integer by a new prompt on a new line, indicating that square x = x * x the process can begin again with another smaller :: (Integer,Integer) à Integer expression smaller (x,y)= if x £ y then x else y ? 6 * 7 Given the previous script, the following session is 42 now possible: This sequence of interactions between ? square 3768 ? square(smaller(5,3+4)) user and computer is called a session. 14197824 25 Chapter 15: Functional Programming 31 Chapter 15: Functional Programming 32

Haskell: scripts Haskell: scripts

The purpose of a definition of a function is Some expressions can be evaluated to introduce a binding associating a given without having to provide a context. name with a given definition. n Those operations are called primitives (the n A set of bindings is called an environment or rules of simplification are build into the context. evaluator). Expressions are always evaluated in some context and can contain occurrences of the names found Basic operations of arithmetic. in that context. Other libraries can be loaded. The Haskell evaluator uses the definitions At any point, a script can be modified and associated with those names as rules for simplifying expressions. resubmitted to the evaluator.

Chapter 15: Functional Programming 33 Chapter 15: Functional Programming 34

Haskell: first things to remember Haskell: evaluation

Scripts are collections of definitions supplied by The computer evaluates an expression by the programmer. reducing it to its simplest equivalent form Definitions are expressed as equations between and displaying the result. certain kinds of expressions and describe mathematical functions. n This process is called evaluation, simplification,

n Definitions are accompanied by type signatures. or reduction. During a session, expressions are submitted for n Example: square(3+4) evaluation n An expression is canonical or in normal form If n These expressions can contain references to the functions defined in the script, as well as references it cannot be further reduced. to other functions defined in libraries.

Chapter 15: Functional Programming 35 Chapter 15: Functional Programming 36

6 Haskell: evaluation Getting Started with Hugs

% hugs A characteristic feature of functional Type : ? for help programming is that if two different Prelude> 6*7 reduction sequences terminate, they lead 42 to the same result. Prelude> square(smaller(6,9)) ERROR – Undefined variable “smaller” n For some expressions some ways of simplification will terminate while other do not. Prelude> sqrt(16) 4.0 n Example: three infinity Prelude> :load example1.hs n Lazy evaluation guarantees termination Reading file “example1.hs” whenever termination is possible Main> square(smaller(6,9))

Chapter 15: Functional Programming 37 36 Chapter 15: Functional Programming 38

Getting Started with Hugs

Typing :? In Hugs will produce a list of possible commands. Typing :quit will exit Hugs Typing :reload will repeat last load command Typing :load will clear all files

Chapter 15: Functional Programming 39

7