Skip to content

Commit

Permalink
Add Int.sum
Browse files Browse the repository at this point in the history
This method takes an Iter and sums its values, meaning that instead of
this:

    vals.into_iter.reduce(0, fn (acc, val) { acc + val })

You can write this instead:

    Int.sum(vals.into_iter)

Changelog: added
  • Loading branch information
yorickpeterse committed Apr 10, 2024
1 parent ecbe1a6 commit a783979
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
11 changes: 10 additions & 1 deletion std/src/std/int.inko
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import std.cmp (Compare, Equal, Ordering)
import std.float (ToFloat)
import std.fmt (Format as FormatTrait, Formatter)
import std.hash (Hash, Hasher)
import std.iter (Peekable)
import std.iter (Iter, Peekable)
import std.ops (
Add, BitAnd, BitOr, BitXor, Divide, Modulo, Multiply, Power, ShiftLeft,
ShiftRight, Subtract, UnsignedShiftRight,
Expand Down Expand Up @@ -194,6 +194,15 @@ class builtin Int {
}
}

# Sums the values of `iterator` into a single `Int`.
#
# # Examples
#
# Int.sum([10, 20, 30].into_iter) => 60
fn pub static sum[I: Iter[Int]](iterator: move I) -> Int {
iterator.reduce(0, fn (acc, val) { acc + val })
}

# Formats `self` as a `String` in the given format.
#
# # Examples
Expand Down
2 changes: 2 additions & 0 deletions std/test/std/test_int.inko
Original file line number Diff line number Diff line change
Expand Up @@ -385,4 +385,6 @@ fn pub tests(t: mut Tests) {
t.equal(2.checked_pow(2), Option.Some(4))
t.equal(MAX.checked_pow(2), Option.None)
})

t.test('Int.sum', fn (t) { t.equal(Int.sum([10, 20, 30].into_iter), 60) })
}

0 comments on commit a783979

Please sign in to comment.