I think I would write it as @chenglou does. Something along the lines of
let process' = (f, initialState, arr, result) => {
let rec loop = (state, i) => {
if i >= 0 {
let newState = f(arr[i], state)
result[i] = newState
loop(newState, i - 1)
}
}
loop(initialState, Array.length(arr) - 2)
}
(The same solution, just local-binding the loop function so it is local and doesn’t pollute the scope more than is necessary).
I can definitely see why you might want something like let mut x =...
since that’s somewhat what Rust does. Though one important thing is that mut
is a modifier in Rust, so you can have stuff such as let (a, mut b) = ...
making b mutable, but not a. The OCaml root, which to a certain extent informed the type system of Rescript, puts the designator on the value, and not on the variable. I have a hunch this is why you have the current situation and why it isn’t that easy to make the change in the first place.
There is also a question of what you want to encourage in programming solutions. If you provide affordance toward easy handling of ref-cells, you will make that more prevalent in programs. If you provide pressure against ref-cells, but still allow them, you encourage people to use a more functional style in their programming. However, because you still have them, you can employ mutation when it is required (for efficiency reasons of the resulting program), or if the algorithm / data structure is easier to describe with mutation.
As for reduce
, I tend to shy away from them in the case where you aren’t processing the full array. You need to use extra code to “select” the right array subset, and unless you have an efficient way of doing so, built into your usual language vocabulary, a more direct approach tend to be easier to read. Also, we are more doing something for its side-effect, namely updating result
, and a reducer wants to end up with a final value we can output. I.e., we can write this in terms of reduce, but it’s different enough that I would rather see a recursion loop, because that would make me think about what is happening.