Given an integer array nums, a reducer function fn, and an initial value init, return the final result obtained by executing the fn function on each element of the array, sequentially, passing in the return value from the calculation on the preceding element.
This result is achieved through the following operations: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ... until every element in the array has been processed. The ultimate value of val is then returned.
If the length of the array is 0, the function should return init.
Please solve it without using the built-in Array.reduce method.
Define a function that takes nums, fn, and init. Start with ans = init, then for each element, update ans = fn(ans, num). Return ans at the end. If nums is empty, return init immediately.
from typing import List, Callable
defreduce(nums: List[int], fn: Callable[[int, int], int], init: int) -> int:
ans = init
for num in nums:
ans = fn(ans, num)
return ans