Functions as first-class values

In most languages, functions can be passed around just like numbers or strings. That's the foundation of everything from callbacks to React hooks.

Write a function applyTwice that takes:

  • a function f that takes one integer and returns one integer
  • a starting integer n

…and returns the result of applying f to n twice.

applyTwice(x => x + 3, 7)  β†’  13   // (7+3)+3
applyTwice(x => x * 2, 5)  β†’  20   // (5*2)*2

Your program receives two command-line arguments:

  1. The operation: add:<k> or mul:<k>
  2. The starting integer

Print the result.


Constraints

  • applyTwice must accept a function as its first argument β€” do not hardcode the operation inside it.
  • Supported ops: add:<k> and mul:<k>.
Ad SpaceGoogle AdSense active for guests & free-tier learners.