




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































Preface i
1.1 Functional languages 1.2 Programming with functions 1.3 Standard functions 1.4 Defining functions 1.5 Types
1.6 Synonym definitions 1.7 Modules 1.8 O v e r v i e w 1.9 Exercises
Many centuries before the advent of digital computers, functions have been used to de- scribe the relation between input and output of processes. Computer programs, too, are descriptions of the way a result can be computed, given some arguments. A natural way to write a computer program is therefore to define some functions and applying them to con- crete values.
We need not to constrain ourselves to numeric functions. Functions can also be defined that have, e.g., sequences of numbers as argument. Also, the result of a function can be some compound structure. In this way, functions can be used to model processes with large, structured, input and output.
The first programming language based on the notion of functions was LISP, developed in the early 60s by John McCarthy. The name is an abbreviation of `list processor', which re- flects the fact that functions can operate on lists (sequences) of values. An important fea- ture of the language was that functions themselves can be used as argument to other func- tions.
Experience with developing large programs has showed that the ability to check programs before they are ran is most useful. Apart from the syntactical correctness of a program, the compiler can check whether it actually makes sense to apply a given function to a particular argument. This is called type checking. For example, a program where the square root of a list is taken, is considered to be incorrectly typed and is therefore rejected by the compiler.
In the last decade, functional languages have been developed in which a type system ensures the type correctness of programs. Some examples are ML, MIRANDA, HASKELL, and CLEAN. As functions can be used as arguments of other functions, functions are `values' in some sense. The ability of defining functions operating on functions and having functions as a result (higher-order functions) is an important feature of these functional languages.
In this book, we will use the language CLEAN. Compared to the other languages mentioned above, CLEAN provides an accurate control over the exact manipulations needed to exe- cute a program. There is a library that offers easy access to functions manipulating the user interface in a platform independent way. Also, the type system is enriched with uniqueness types, making it possible for implementations to improve the efficiency of program execu-
I.1 INTRODUCTION TO FUNCTIONAL PROGRAMMING 3
Start = sin 0.3 * sin 0.3 + cos 0.3 * cos 0.
A sequence of numbers can be put into a list in CLEAN. Lists are denoted with square brackets. There is a number of standard functions operating on lists: Start = sum [1..10]
In this example [1..10] is the CLEAN notation for the list of numbers from 1 to 10. The standard function sum can be applied to such a list to calculate the sum ( 55 ) of those num- bers. Just as with sqrt and sin the (round) parentheses are redundant when calling the func- tion sum.
A list is one of the ways to compose data, making it possible to apply functions to large amounts of data. Lists can also be the result of a function. Execution of the program Start = reverse [1..10]
will display the list [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] to the user. The standard function reverse reverses the order of a list.
There are many more standard functions manipulating lists. What they do can often be guessed from the name: length determines the length of a list, sort sorts the elements of a list from small to large.
In a single expression, several functions can be combined. It is, for example, possible to first sort a list and then reverse it. The program Start = reverse (sort [1,6,2,9,2,7])
will sort the numbers in the list, and then reverse the resulting list. The result [9, 7, 6, 2, 2, 1] is displayed to the user. As conventional in mathematical literature, g (f x) means that f should be applied to x and g should be applied to the result of that. The parentheses in this example are (even in CLEAN!) necessary, to indicate that (f x) as a whole is an argument of g.
1.2.2 Defining new functions
In a functional programming language it is possible to define new functions by yourself. The function can be used like the predefined functions from the standard environment, in the Start expression and in other function definitions. Definitions of functions are always part of a module. Such a module is always stored in a file.
For instance, a function fac, which calculates the factorial of a number, can be defined. The factorial of a number n is the product of all numbers between 1 and n. For example, the factorial of 4 is 123*4 = 24. The fac function and its use in the Start expression can be defined in a CLEAN program: fac n = prod [1..n]
Start = fac 6
The value of the Start expression, 720 , will be shown to the user.
Functions that are defined can be used in other functions as well. A function that can make use of the fac function is over. It calculates the number of possibilities in which k objects can be chosen from a collection of n objects. According to statistics literature this number equals
n
n! k! ( n − k )!
These numbers are called binomial coefficients, ( (^) k
n ) is pronounced as n over k. The defi- nition can, just as with fac, be almost literally (n! means the factorial of n) been written down in CLEAN: over n k = fac n / (fac k * fac (n-k))
Start = over 10 3
4 FUNCTIONAL PROGRAMMING IN CLEAN
The arguments appearing on the left-hand side of a function definition, like n and k in the function over, are called the formal arguments or formal parameters of the function. For using it, one applies a function with actual arguments (also called actual parameters ). For example, on the right-hand side of the start expression the function over is applied to the actual argu- ments 3 and 120. The actual argument corresponding to n is 3, and the actual argument cor- responding to k is 120.
When run, this program displays the number of ways a committee of three persons can be chosen from a group of ten people ( 120 ).
Apart from functions, also constants may be defined. This might be useful for definitions like pi = 3.
Another example of a constant is Start, which must be defined in every program. In fact, constants are just functions without arguments.
1.2.3 Program evaluation with functions
So, a functional program generally consists of a collection of function definitions and one initial expression (the Start expression). The execution of a functional program starts with the evaluation of the initial expression (the Start expression). This initial expression is re- peatedly replaced by its result after evaluating a function application. This process of evaluation is called reduction. One step of the process, evaluating a single function ap- plication, is called a reduction step. This step consists of the replacement of a part of the ex- pression which matches a function definition (this part is called the redex , a red ucable ex- pression) with (a copy of) the function definition in which for the formal arguments uni- formly the actual arguments are substituted. When the expression contains no redexes re- duction cannot take place anymore: the expression is said to be in normal form. In principle, the normal form of the start expression is the result of the evaluation of the program.
Suppose we define a function as follows
extremelyUsefulFunction x = (x + 19) * x
A program using this function consists then of a start expression
Start = extremelyUsefulFunction 2
This expression will be reduced as follows (the arrow → indicates a reduction step, the re- dex which is reduced is underlined): Start → extremelyUsefulFunction 2 → (2 + 19) * 2 → 21 * 2 → 42
So, the result of evaluating this extremely useless program is 42. In other words, 42 is the normal form of extremelyUsefulFunction 2.
1.3.1 Names of functions and operators
In the CLEAN standard environment, a large number of standard functions is predefined. We will discuss some of them in the subsections below.
The rules for names of functions are rather liberal. Function names start with a letter, fol- lowed by zero or more letters, digits, or the symbol _ or `. Both lower and upper case let- ters are allowed, and treated as distinct symbols. Some examples are:
6 FUNCTIONAL PROGRAMMING IN CLEAN
^ raising a number to a power
Some standard functions on real numbers are: sqrt the square root function sin the sine function ln the natural logarithm exp the exponential function (e-to-the-power-of)
1.3.3 Predefined functions on Booleans
The operator < determines whether a number is smaller than another number. The result is the constant True (if it is true) or the constant False (if it is false). For example, the value of 1<2 is True.
The values True and False are the only elements of the set of truth values or Boolean values (named after the English mathematician George Boole, who lived from 1815 till 1864). Functions (and operators) resulting such a value are called Boolean functions or predicates.
Next to < there is also an operator > (greater than), an operator <= (smaller or equal to), and an operator >= (greater or equal to). Furthermore, there is the operator == (equal to) and an operator <> (not equal to).
Results of Boolean functions can be combined with the operators && (and') and || (or'). The operator && only returns True if the results left and right are true: Start = 1<2 && 3<
will show the result True to the user. The `or' operator needs only one of the two state- ments to be true (both may be true as well), so 1==1 || 2==3 will yield True. There is a func- tion not swapping True and False. Furthermore there is a function isEven which checks whe- ther an integer number is even.
1.3.4 Predefined functions on lists
In the standard module StdList a number of functions operating on lists is defined. Some functions on lists have already been discussed: length determines the length of a list, sum cal- culates the sum of a list of whole numbers.
The operator ++ concatenates two lists. For example, Start = [1,2] ++ [3,4,5]
will show the list [1,2,3,4,5].
The function and operates on a list of which the elements are Booleans; and checks if all the elements in the list are True. For example, the expression and [1<2, 2<3, 1==0] returns False.
Some functions have two parameters. The function take operates on a number and a list. If the number is n, the function will return the first n elements of the list. For example, take 3 [2..10] returns the list [2,3,4].
1.3.5 Predefined functions on functions
In the functions discussed so far, the parameters were numbers, Booleans or lists. Howe- ver, the argument of a function can be a function itself, too! An example of that is the function map, which takes two arguments: a function and a list. The function map applies the argument function to all the elements of the list. It is defined in the standard module StdList.
Some examples of the use of the map functions are: Start = map fac [1,2,3,4,5]
Applying the fac function to all five numbers, this shows the list [1,2,6,24,120].
Running the program Start = map sqrt [1.0,2.0,3.0,4.0]
I.1 INTRODUCTION TO FUNCTIONAL PROGRAMMING 7
shows the list [1.0, 1.41421, 1.73205, 2.0], and the program Start = map isEven [1..8]
checks all eight numbers for even-ness, yielding a list of Boolean values: [False, True, False, True, False, True, False, True].
1.4.1 Definition by combination
The easiest way to define functions is by combining other functions and operators, for ex- ample by applying predefined functions that have been imported: fac n = prod [1..n] square x = x * x
Functions can also have more than one argument: over n k = fac n / (fac k * fac (n-k)) roots a b c = [ (~b+sqrt(bb-4.0ac)) / (2.0a) , (~b-sqrt(bb-4.0ac)) / (2.0a) ]
The operator ~ negates its argument. See 1.3.2 and Chapter 2 for the difference between 2 and 2.0.
Functions without arguments are commonly known as `constants': pi = 3. e = exp 1. These examples illustrate the general form of a function definition:
In definitions of functions with a Boolean result, at the right hand side of the =-symbol an expression of Boolean value is given: negative x = x < 0 positive x = x > 0 isZero x = x == 0
Note, in this last definition, the difference between the =-symbol and the ==-operator. A single equals'-symbol (=) separates the left-hand side from the right-hand side in function definitions. A doubleequals'-symbol (==) is an operator with a Boolean result, just as < and >.
In the definition of the roots function in the example above, the expressions sqrt(bb- 4.0ac) and (2.0a) occur twice. Apart from being boring to type, evaluation of this kind of expression is needlessly time-consuming: the identical subexpressions are evaluated twice. To prevent this, in CLEAN it is possible to name a subexpression, and denote it only once. A more efficient definition of the function roots would be: roots a b c = [ (~b+s)/d , (~b-s)/d ] where s = sqrt (bb-4.0ac) d = 2.0a
The word where is not the name of a function. It is one of the `reserved words' that where mentioned in subsection 1.3.1. Following the word where in the definition, again some defi- nitions are given. In this case the constants s and d are defined. These constants may be used in the expression preceding the where. They cannot be used elsewhere in the program;
I.1 INTRODUCTION TO FUNCTIONAL PROGRAMMING 9
ample, the sqrt function is not defined for negative numbers, and the / operator is not de- fined for 0 as its second argument. These functions are called partial functions.
You can define functions with different patterns as formal argument: sum [] = 0 sum [x] = x sum [x,y] = x+y sum [x,y,z] = x+y+z
This function can be applied to lists with zero, one, two or three elements (in the next sub- section this definition is extended to lists of arbitrary length). In each case, the elements of the list are added. On use of this function, it is checked whether the actual argument `matches' one of the patterns. Again, the definitions are tried in textual order. For example, the call sum [3,4] matches the pattern in the third line of the definition: The 3 corresponds to the x and the 4 to the y.
As a pattern, the following constructions are allowed:
Using patterns, we could for example define the logical conjunction of two Boolean func- tions: AND False False = False AND False True = False AND True False = False AND True True = True
By naming the first element of a list, two useful functions can be defined, as is done in the module StdList: hd [x:y] = x tl [x:y] = y
The function hd returns the first element of a list (its head'), while the function tl returns all but the first element (thetail' of the list). These functions can be applied to almost all lists. They are not defined, however, for the empty list (a list without elements): an empty list has no first element, let alone a `tail'. This makes hd and tl partial functions.
Note the difference in the patterns (and expressions) [x:y] and [x,y]. The pattern [x:y] de- notes a list with first element (head) x and rest (tail) y. This tail can be any list, including the empty list []. The pattern [x,y] denotes a list of exactly two elements, the first one is called x, and the other one y.
1.4.4 Definition by induction or recursion
In definitions of functions, other functions may be used. But also the function being defi- ned may be used in it's own definition! A function which is used in its own definition is called a recursive function (because its name `re-(oc)curs' in its definition). Here is an example of a recursive definition: fac n | n==0 = 1 | n>0 = n * fac (n-1)
The name of the function being defined (fac) occurs in the defining expression on the right hand side of the =-symbol.
Another example of a recursively defined function is `raising to an integer power'. It can be defined as: power x n
10 FUNCTIONAL PROGRAMMING IN CLEAN
| n==0 = 1 | n>0 = x * power x (n-1)
Also, functions operating on lists can be recursive. In the previous subsection we intro- duced a function to determine the length of some lists. Using recursion we can define a function sum for lists of arbitrary length: sum list | list == [] = 0 | otherwise = hd list + sum (tl list)
Using patterns we can also define this function in a much more readable way: sum [] = 0 sum [first: rest] = first + sum rest
Using patterns, you can give the relevant parts of the list a name directly (like first and rest in this example). In the definition that uses guarded expressions to distinguish the cases, auxiliary functions hd and tl are necessary.
Using patterns, we can define a function length that operates on lists: length [] = 0 length [first:rest] = 1 + length rest
The value of the first element is not used (only the fact that a first element exists). For cases like this, it is allowed to use the ‘’ symbol instead of an identifier: length [] = 0 length [:rest] = 1 + length rest
Recursive functions are generally used with two restrictions:
In the definition of fac given above, the base case is n==0; in this case the result can be de- termined directly (without using the function recursively). In the case that n>0, there is a recursive call, namely fac (n-1). The argument in the recursive call (n-1) is, as required, smaller than n.
For lists, the recursive call must have a shorter list as argumen. There should be a non- recursive definition for some finite list, usually the empty list.
1.4.5 Local definitions, scope and lay-out
If you want to define a function to solve a certain problem you often need to define a number of additional functions each solving a part of the original problem. Functions fol- lowing the keyword where are locally defined which means that they only have a meaning within the surrounding function. It is a good habit to define functions that are only used in a particular function definition, locally to the function they belong. In this way you make it clear to the reader that these functions are not used elsewhere in the program. The scope of a definition is the piece of program text where the definition can be used. The box in figure 1.1 shows the scope of a local function definition, i.e. the area in which the locally defined function is known and can be applied. The figure also shows the scope of the arguments of a function. If a name of a function or argument is used in an expression one has to look for a corresponding definition in the smallest surrounding scope (box). If the name is not de- fined there one has to look for a definition in the nearest surrounding scope and so on.
function args | guard1 = expression | guard2 = expression where function args = expression
Figure 1.1 : Defining functions and values locally for a function alternative.