Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Make combine faster #29

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions src/Result/Extra.elm
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,24 @@ mapBoth errFunc okFunc result =
Also known as `sequence` on lists.
-}
combine : List (Result x a) -> Result x (List a)
combine =
List.foldr (Result.map2 (::)) (Ok [])
combine list =
combineHelp list []
|> Result.map List.reverse

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you move the List.reverse into the [] -> branch of combineHelp then you don't need to Result.map over it or pipe. Will probably only add 0.000001% better performance 😅

Copy link
Author

@jfmengels jfmengels Oct 21, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, you'd be surprised... It's not the same kind of improvement, but for small lists, it's a noticeable improvement (compared to the version I already proposed).

https://ellie-app.com/fDcGZNzBFzGa1

Screenshot from 2021-10-21 20-30-32
Screenshot from 2021-10-21 20-31-15
Screenshot from 2021-10-21 20-32-08

You're absolutely right, and I don't know why I didn't do this in the first place (well, probably because adding List.reverse was something I realized I needed to do a lot later 🤦).

I updated the PR 👍

I didn't benchmark on the Err case but it should also improve performance 👍



combineHelp : List (Result x a) -> List a -> Result x (List a)
combineHelp list acc =
case list of
head :: tail ->
case head of
Ok a ->
combineHelp tail (a :: acc)

Err x ->
Err x

[] ->
Ok acc


{-| Map a function producing results on a list
Expand Down