# Functional Programming(Lec05)

## yukita@k.hosei.ac.jp

### •Function

A function can be defined via the **Function**

form.

Let us check how it works.

Let us do a systematic experiment using Map.

A function can be defined in other forms.

Let us examine the internal representations of f and g.

#### •Note

The Function form is not a pure function. This can be seen from the following sequence of operations.

We assigned value 100 to variable x before using parameter x in the subsequent function definition. However, there was no interferance between them. This shows that the **Function**

form is not a pure function but a kind of function like thing that returns a pure function.

We can do the same task in a way where there is no possibility of this kind of confusion.

### •Map in more details

Although the default level in Map is 1, the result was produced with level 2. This is because the ToUpperCase function does the list mapping automatically. To see this, try the following.

### •Apply

Compare the **Apply**

and **Map**

functions.

The difference is fully understood if we use the full form for {a,b,c}.

So, **{a,b,c}**

is equivalent to **List[a,b,c]**

. Let us do the comparison again in this full form.

Now, the difference is clear. **Apply**

replaces the head part of its second argument with the first argument while **Map**

makes the given function plunge into lower level of the list. We will more clearly understand this by the following examples.

### •Nest and NestList

### •FixedPoint

Guess what happens if a list of numbers is passed to the following function.

### •Exercises

#### •Problem 1

We have implemented the bubble sort algorithm as a fixed point of the following function **f**

.

Reimplement f using Do-loop. Present an example that demonstrates the validity of your implementation.

Hint: Try to fill in the blanks.

##### •Solution

#### •Problem 2

Let g be a function that accepts a list of real numbers as its only argument and return a new list whose each element is replaced with the arithmetic mean of the neighboring elements, and whose both end elements are unchanged. Implement g. Then, using FixedPoint, obtain the result as follows.

Use the **ListPlot **

function to visualize **data**

and **result**

.

##### •Solution

Converted by *Mathematica*
(May 20, 2003)