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) = 3nquadruple
: take the quadruple of a number – q(n) = 4nsquare
: 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.
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.
triple 60
quadruple 12
square 12
cube 6
180
48
144
216
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:
def apply(f, x):
int apply(int (*f)(int), int x);
apply :: (Int -> Int) -> Int -> Int
int apply(int (*f)(int), int x);
Submit your solution to be graded according to the following list:
To compute the triple of 60:
triple
;triple(60)
;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:
qsort
uses a callback to compare elements;map
take a functional argument.
Copyright © 2020-2021 Rudy Matela
This text is available under the CC BY-SA 4.0 license.
Originally available on cscx.org/apply