Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add .sum to Vector #1702

Merged
merged 3 commits into from
Apr 28, 2021
Merged
Show file tree
Hide file tree
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
18 changes: 18 additions & 0 deletions distribution/std-lib/Standard/src/Base/Data/Vector.enso
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,24 @@ type Vector
True -> this.tail.fold this.head function
False -> Error.throw Nothing

## Computes the sum of the values in the vector.

For this method to be defined, the elements of the vector must be able to
have the `+` operator used to combine them.

> Example
In the following example, we'll compute the sum of all elements of a
vector.

[0, 1, 2].sum
sum : (Any ! Nothing)
sum =
result = Panic.recover <| this.reduce (+)
result.map_error x->case x of
No_Such_Method_Error _ _ -> Nothing
Nothing -> Nothing
_ -> Panic.throw x

## Checks whether a predicate holds for at least one element of this vector.

Arguments:
Expand Down
5 changes: 5 additions & 0 deletions test/Tests/src/Data/Vector_Spec.enso
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ spec = Test.group "Vectors" <|
[1,2,3].reduce (+) . should_equal 6
[].reduce (+) . should_fail_with Nothing

Test.specify "should allow summing elements if they define +" <|
[1,2,3].sum . should_equal 6
[].sum . should_fail_with Nothing
[T 1 2, T 3 4].sum . should_fail_with Nothing

Test.specify "should check exists" <|
vec = [1, 2, 3, 4, 5]
vec.exists (ix -> ix > 3) . should_be_true
Expand Down