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:

  1. triple: take the triple of a number – t(n) = 3n
  2. quadruple: take the quadruple of a number – q(n) = 4n
  3. square: take the square of a number – s(n) = n²
  4. 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


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:


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


To compute the triple of 60:

  1. declare a function triple;
  2. don’t use triple(60);
  3. 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:

try first: triple power

index | submit | rank | book

Copyright © 2020-2023 Rudy Matela
All rights reserved