PHP: A multiplier factory

A function that builds new functions: the closure remembers the number it was made with.

What to build

A program that multiplies a list with a closure.

Requirements

  • Write makeMultiplier(int $m) that returns a closure multiplying its argument by m.
  • Read m, then n and a line with n integers. Print every number multiplied by m, separated by spaces.

Input

Line 1: m. Line 2: n. Line 3: n integers.

Output

One line.

Constraints

-100 ≤ m ≤ 100; 1 ≤ n ≤ 50; numbers between -1000 and 1000.

Example

Input:

3
4
1 2 3 4

Output:

3 6 9 12

Why it works

The arrow function captures m when it is created, so each closure made by the factory keeps its own number.

Examples

Example 1 · Input
3
4
1 2 3 4
Expected output
3 6 9 12
Example 2 · Input
-2
3
5 0 -5
Expected output
-10 0 10

Hints

Hint 1

function makeMultiplier(int $m): Closure { return fn($x) => $x * $m; }

Hint 2

Pass the closure to array_map to apply it to the whole list.

Solution

Show one correct solution (try it yourself first)
<?php
function makeMultiplier(int $m): Closure
{
    return fn($x) => $x * $m;
}

$m = (int) trim(fgets(STDIN));
$n = (int) trim(fgets(STDIN));
$nums = array_map('intval', explode(" ", trim(fgets(STDIN))));
$times = makeMultiplier($m);
echo implode(" ", array_map($times, $nums)), "\n";

▶ Open this solution in the compiler

Lesson: Scope and closures →