Skip to content

Add iterator.take_while_inclusive #389

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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
- The `float` module gains the `loosely_equals` function.
- The `io` module gains `print_error` and `println_error` functions for
printing to stderr.
- The `iterator` module gains the `take_while_inclusive` function.
- The `io.debug` function now prints to stderr instead of stdout when using
the Erlang target or running in Node.js (but still uses `console.log`
when running as JavaScript in a browser)
Expand Down
39 changes: 39 additions & 0 deletions src/gleam/iterator.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -653,6 +653,45 @@ pub fn take_while(
|> Iterator
}

fn do_take_while_inclusive(
continuation: fn() -> Action(element),
predicate: fn(element) -> Bool,
continue: Bool,
) -> fn() -> Action(element) {
fn() {
case continue {
False -> Stop
True ->
case continuation() {
Stop -> Stop
Continue(e, next) ->
Continue(e, do_take_while_inclusive(next, predicate, predicate(e)))
}
}
}
}

/// Creates an iterator that yields elements while the predicate returns `True`,
/// and also yields the element for which the predicate first returned `False`.
///
/// ## Examples
///
/// ```gleam
/// > from_list([1, 2, 3, 2, 4])
/// > |> take_while_inclusive(satisfying: fn(x) { x < 3 })
/// > |> to_list
/// [1, 2, 3]
/// ```
///
pub fn take_while_inclusive(
in iterator: Iterator(element),
satisfying predicate: fn(element) -> Bool,
) -> Iterator(element) {
iterator.continuation
|> do_take_while_inclusive(predicate, True)
|> Iterator
}

fn do_drop_while(
continuation: fn() -> Action(element),
predicate: fn(element) -> Bool,
Expand Down
7 changes: 7 additions & 0 deletions test/gleam/iterator_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,13 @@ pub fn take_while_test() {
|> should.equal([1, 2])
}

pub fn take_while_inclusive_test() {
iterator.from_list([1, 2, 3, 2, 4])
|> iterator.take_while_inclusive(satisfying: fn(x) { x < 3 })
|> iterator.to_list
|> should.equal([1, 2, 3])
}

pub fn drop_while_test() {
iterator.from_list([1, 2, 3, 4, 2, 5])
|> iterator.drop_while(satisfying: fn(x) { x < 4 })
Expand Down