Multiplier function using closure
Problem Statement
Design and implement a multiplier function using closures that allows dynamic creation of functions to multiply numbers by a given factor.
This exercise tests understanding of:
📋 Problem Description
You are required to implement a function factory that creates multiplier functions.
For example:
You must ensure that each returned function remembers its multiplier value (closure behavior) even after the original scope has finished execution.
🧱 Core Requirements
1. Function Definition
Implement a higher-order function:
1
2def createMultiplier(factor):
3 # returns a function that multiplies input by 'factor'2. Closure Behavior
The returned function should remember the factor value passed during its creation, even if used later.
3. Usage Example
1
2
3times2 = createMultiplier(2)
4times5 = createMultiplier(5)
5
6print(times2(10)) # Output: 20
7print(times5(10)) # Output: 50⚙️ Functional Requirements
🧩 Example Scenario
1
2def createMultiplier(factor):
3 def multiplier(x):
4 return x * factor
5 return multiplier
6
7times3 = createMultiplier(3)
8times10 = createMultiplier(10)
9
10print(times3(7)) # Output: 21
11print(times10(7)) # Output: 70⚙️ Non-Functional Requirements
Aspect and Requirement
Encapsulation
Multiplier value (factor) must not be exposed globally.
Reusability
The function should work for any valid numeric multiplier.
Immutability
The multiplier constant inside closure should remain unchanged.
Simplicity
No use of global variables or classes.
🧠 Design Discussion Points
✅ Deliverables
🚀 Stretch Goals