Project

General

Profile

Actions

Feature #17016

open

Enumerable#accumulate

Added by parker (Parker Finch) over 1 year ago. Updated 7 months ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:99078]

Description

Proposal

UPDATE: Changed proposed method name from #scan_left to #accumulate.

Add an #accumulate method to Enumerable.

Background

#accumulate is similar to #inject, but it accumulates the partial results that are computed. As a comparison:

[1, 2, 3].inject(0, &:+) => 6
[1, 2, 3].accumulate(0, &:+) => [0, 1, 3, 6]

Notably, the accumulate operation can be done lazily since it doesn't require processing the entire collection before computing a value.

I recently described #accumulate, and its relationship to #inject, more thoroughly in this blog post.

Reasoning

We heavily rely on the accumulate operation. We use an event-sourcing pattern, which means that we are scanning over individual "events" and building up the corresponding state. We rely on the history of states and need to do this lazily (we stream events because they cannot fit in memory). Thus the scan operation is much more applicable than the inject operation.

We suspect that there are many applications that could leverage the scan operation. This question would be more easily answered by #accumulate. It is a natural fit for any application that needs to store the incrementally-computed values of an #inject, and a requirement for an application that needs to use #inject while maintaining laziness.

Implementation

There is a Ruby implementation of this functionality here and an implementation in C here.

Update: nobu (Nobuyoshi Nakada) has provided an alternative implementation here.

Counterarguments

Introducing a new public method is committing to maintenance going forward and expands the size of the Ruby codebase -- it should not be done lightly. I think that providing the functionality here is worth the tradeoff, but I understand any hesitation to add yet more to Ruby!


Files

scan_left_example.rb (2.93 KB) scan_left_example.rb Small script showing `scan` usage with other approaches to the same behavior parker (Parker Finch), 07/10/2020 08:52 PM
Actions

Also available in: Atom PDF