Why doesn't Array2D have a fold operation?

I just ran into a situation where it would be useful to have fold / foldi methods on Array2D, and I wondered if there is a reason why Array2D doesn't have them.

Since my 2d array is large enough, I would not want to convert it to some other format first.

Is this just a rare use case or is there a technical reason why these methods have not been added? Or is there a way to achieve the same without touching the data in the array (as in the case of a move)?


source to share

2 answers

I think that this feature in a standard module Array2D

would be quite useful. You can open the issue for the Visual F # repository and help us add it :-).

In addition to what @scrwtp wrote, you can also use a more direct variable implementation. For basic functionality like this, I think using mutation is fine and it will be a little faster:

let foldi (folder: int -> int ->  -> 'T -> 'S) (state: 'S) (array: 'T[,]) =
    let mutable state = state
    for x in 0 .. Array2D.length1 array - 1 do
        for y in 0 .. Array2D.length2 array - 1 do
            state <- folder x y state (array.[x, y])




I don't think there is any particular reason why it Array2D

doesn't come with these features in the standard as it has map

/ mapi

. The use cases where you want to process a multidimensional array are probably better served using a jagged array, so there is little incentive to add them.

There is no reason why you cannot define them yourself.

Here's an example of a fold:

let foldi (folder: int -> int ->  -> 'T -> 'S) (state: 'S) (array: 'T[,]) =
    seq {
        for x in 0 .. Array2D.length1 array - 1 do
            for y in 0 .. Array2D.length2 array - 1 do
                yield (x, y, array.[x, y])
    |> Seq.fold (fun acc (x, y, e) -> folder x y acc e) state


For regular creases and a more detailed explanation of how it works, you can take a look here .



All Articles