Hone logo
Hone
Problems

Go Closures: Dynamic Function Factory

Closures are a powerful feature in Go that allow functions to "remember" the environment in which they were created, even after the outer function has finished executing. This challenge will test your understanding of closures by having you create a dynamic function factory that generates functions with pre-set configurations.

Problem Description

Your task is to implement a function called MakeMultiplier that acts as a factory for creating multiplier functions. MakeMultiplier should accept an integer factor as an argument and return a new function. The returned function should, when called with an integer n, return the result of n * factor.

This is a classic example of using closures to create stateful functions. The returned multiplier function will "close over" the factor variable from its enclosing MakeMultiplier function.

Key Requirements:

  • Implement a function MakeMultiplier(factor int) func(int) int.
  • The returned function must be a closure.
  • The returned function must correctly multiply its input by the factor it was created with.

Expected Behavior:

When MakeMultiplier(5) is called, it should return a function. Let's call this returned function multiplyByFive. If multiplyByFive(10) is then called, the output should be 50. Similarly, if MakeMultiplier(3) is called, it should return a function, let's call it multiplyByThree. Calling multiplyByThree(7) should result in 21.

Edge Cases:

  • Consider the behavior when factor is zero or negative. The closure should handle these values correctly.
  • Consider the behavior when the input n to the returned function is zero or negative.

Examples

Example 1:

Input:
factor = 5
n = 10

Output:
50

Explanation:
`MakeMultiplier(5)` returns a function. When this function is called with `10`, it multiplies `10` by the captured `factor` of `5`, resulting in `50`.

Example 2:

Input:
factor1 = 3
n1 = 7

factor2 = -2
n2 = 4

Output:
21
-8

Explanation:
`MakeMultiplier(3)` returns a multiplier for `3`. `3 * 7 = 21`.
`MakeMultiplier(-2)` returns a multiplier for `-2`. `-2 * 4 = -8`.

Example 3:

Input:
factor = 0
n = 100

Output:
0

Explanation:
The closure correctly captures `factor = 0`. Multiplying any number by zero results in zero.

Constraints

  • The factor integer can range from -1000 to 1000.
  • The input integer n to the generated multiplier function can range from -1000 to 1000.
  • The solution should be efficient, with no significant performance bottlenecks.

Notes

  • Think about how Go's anonymous functions and variable scoping work.
  • The returned function needs to maintain access to the factor variable even after MakeMultiplier has returned. This is the essence of a closure.
  • You'll be writing a single Go function, MakeMultiplier.
Loading editor...
go