index
| submit
| rank
| book

## apply – Applying functions

Write a program that is able to perform numeric operations
by means of an `apply`

function.
The purpose here is to exercise taking and passing functions as arguments.

Your program should support four operations:

`triple`

: take the triple of a number – *t(n) = 3n*
`quadruple`

: take the quadruple of a number – *q(n) = 4n*
`square`

: take the square of a number – *s(n) = n²*
`cube`

: take the cube of a number – *c(n) = n³*

For each of the above operations you should define a function
that takes an integer argument and returns an integer result.
You should use these functions in your solution.
However,
you are not allowed to call/apply these functions directly
but instead you should pass them as arguments
to an “apply” function
that handles the function calling / applying.

### Input and Output

The input contains several lines each
with an operation *o* and one integer *x*.
The operation *o* is either `triple`

, `quadruple`

, `square`

or `cube`

.
The integer *x* is given so that *-100 000 < x < 100 000*.

For each line of input,
output should contain an integer *o(x)* indicating
the result of applying *o* to *x*.

#### Example input

```
triple 60
quadruple 12
square 12
cube 6
```

#### Example output

```
180
48
144
216
```

### The “apply” function

Your program should be implemented using an “apply” function
that receives one function and an integer and
returns the result of applying the given function to the given integer.
Please refer to the information for your chosen language:

- Python definition:
`def apply(f, x):`

- C prototype:
`int apply(int (*f)(int), int x);`

- Haskell type:
`apply :: (Int -> Int) -> Int -> Int`

- C++ prototype:
`int apply(int (*f)(int), int x);`

### Scoring

Submit your solution to be graded according to the following list:

- ½: processes input and output correctly
- 2/2: implements the “apply” function

### Hints

To compute the triple of 60:

- declare a function
`triple`

;
- don’t use
`triple(60)`

;
- actually use
`apply(triple,60)`

–
you should perform the application in the body of apply
by means of the given functional value / callback.

This exercise illustrates very simply
how to handle functional values and callbacks
which are key to understanding how some functions are implemented.
For example:

- C’s
`qsort`

uses a callback to compare elements;
- Python’s and Haskell’s
`map`

take a functional argument.

try first: triple power

index
| submit
| rank
| book

Copyright © 2020-2021 Rudy Matela

All rights reserved