elm-community / array-extra

convenience functions for working with Array

Home Page:http://package.elm-lang.org/packages/elm-community/array-extra/latest

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Evaluation of short circuit versions of any and all

kamar535 opened this issue · comments

I got curious as whether or not any and all short circuits, see https://discourse.elm-lang.org/t/how-does-array-extra-all-short-circuit/8947, and it seems like the current implementations does not short circuit.

I've found #26 where it says that the implementation with List.foldl was the fastest. I've tried to search the repository for various implementation candidates and maybe you already evaluated a version of any similar to this which short circuits on the first True?

any isOkay array =
    let
        step index =
            case Array.get index array |> Maybe.map isOkay of
                Just True ->
                    True

                Just False ->
                    step (index + 1)

                Nothing ->
                    False
    in
    step 0
commented

Thanks for the idea. Benchmarking reports (see this pdf) show that recursively getting an element is slower than List.any and fold.

This matches my intuition: get takes log n time n times whereas fold takes n time

Short-circuiting usually halfes the required time. Sadly, Array has no native way of stopping a fold and approximations like what you suggested just have a higher time complexity.

Interesting. I guess Elm arrays are implemented using some kind of trees then, probably because of sharing. I have to learn more about how Elm implements immutable arrays to get rid of my mutable array ways of thinking :-)