Equivalent to Array.scan |> Array.skip 1, but without creating an intermediate array?

The function Array.scanreturns an array of length n+1, where nis the length of its input array, and the first element is the initial state passed to Array.scan. For instance.

[|1;2;3;4|] |> Array.scan (+) 0  // Returns [|0;1;3;6;10|]

However, I usually found that this is not what I wanted: I need an array of length n, without preserving the original state in my output array. I could easily get this result by simply doing:

input |> Array.scan f initialState |> Array.skip 1

But this will create an intermediate array that will be immediately thrown away. Is there a good way to get this result without creating an intermediate array? I could easily implement this myself:

let scanWithoutInitial f initState input =
    let result = Array.zeroCreate (Array.length input)
    let mutable state = initState
    for i = 0 to (Array.length input - 1) do
        state <- f state input.[i]
        result.[i] <- state
    result

, , , F #. , ? , , Array.scan?

+4
1

mapFold :

Array.mapFold (fun acc i -> (acc + i, acc + i)) 0 [|1;2;3;4|] |> fst

brainteaser, ref .

+4

Source: https://habr.com/ru/post/1673625/


All Articles