Skip to content

Commit

Permalink
Add Result.collect
Browse files Browse the repository at this point in the history
This method iterates over a Iter[Result[T, E]], returning a
Result[Array[T, E]], and returning the first Error that it encounters.

This fixes #553.

Changelog: added
  • Loading branch information
yorickpeterse committed May 27, 2023
1 parent c0463c4 commit d85d48a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
24 changes: 24 additions & 0 deletions std/src/std/result.inko
Expand Up @@ -5,6 +5,7 @@
import std::clone::Clone
import std::cmp::Equal
import std::fmt::(Format, Formatter)
import std::iter::Iter

# A type that represents either success (`Ok(T)`) or failure (`Error(E)`).
class pub enum Result[T, E] {
Expand All @@ -14,6 +15,29 @@ class pub enum Result[T, E] {
# The case and value for an error.
case Error(E)

# Collects values from an `Iter[Result[T, E]]` into a `Result[Array[T, E]]`,
# returning the first `Error` encountered when iterating over the iterator.
#
# # Examples
#
# let vals = [Result.Ok(1), Result.Error('oops!'), Result.Ok(2)].into_iter
# let result = Result.collect(vals)
#
# result.error? # => true
fn pub static collect(iter: Iter[Result[T, E]]) -> Result[Array[T], E] {
let vals = []

loop {
match iter.next {
case Some(Ok(val)) -> vals.push(val)
case Some(Error(err)) -> throw err
case _ -> break
}
}

Result.Ok(vals)
}

# Returns `true` if `self` is an `Ok`.
#
# # Examples
Expand Down
9 changes: 9 additions & 0 deletions std/test/std/test_result.inko
@@ -1,7 +1,16 @@
import helpers::(fmt)
import std::iter::Iter
import std::test::Tests

fn pub tests(t: mut Tests) {
t.test('Result.collect') fn (t) {
let foo = [Result.Ok(1), Result.Error('oops!'), Result.Ok(3)].into_iter
let bar: Iter[Result[Int, String]] = [Result.Ok(1), Result.Ok(2)].into_iter

t.equal(Result.collect(foo), Result.Error('oops!'))
t.equal(Result.collect(bar), Result.Ok([1, 2]))
}

t.test('Result.ok?') fn (t) {
let foo: Result[Int, String] = Result.Ok(42)
let bar: Result[Int, String] = Result.Error('oops!')
Expand Down

0 comments on commit d85d48a

Please sign in to comment.