diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/iterator.gleam | 43 | ||||
-rw-r--r-- | src/gleam/list.gleam | 8 |
2 files changed, 32 insertions, 19 deletions
diff --git a/src/gleam/iterator.gleam b/src/gleam/iterator.gleam index 92729a1..6290b05 100644 --- a/src/gleam/iterator.gleam +++ b/src/gleam/iterator.gleam @@ -1,6 +1,8 @@ +import gleam/int import gleam/list import gleam/map.{Map} import gleam/option.{None, Option, Some} +import gleam/order // Internal private representation of an Iterator type Action(element) { @@ -447,29 +449,40 @@ pub fn cycle(iterator: Iterator(a)) -> Iterator(a) { /// /// ```gleam /// > range(from: 1, to: 5) |> to_list -/// [1, 2, 3, 4] +/// [1, 2, 3, 4, 5] /// /// > range(from: 1, to: -2) |> to_list -/// [1, 0, -1] +/// [1, 0, -1, -2] /// /// > range(from: 0, to: 0) |> to_list -/// [] +/// [0] /// ``` /// pub fn range(from start: Int, to stop: Int) -> Iterator(Int) { - let increment = case start < stop { - True -> 1 - False -> -1 - } - - let next_step = fn(current) { - case current == stop { - True -> Done - False -> Next(current, current + increment) - } + case int.compare(start, stop) { + order.Eq -> once(fn() { start }) + order.Gt -> + unfold( + from: start, + with: fn(current) { + case current < stop { + False -> Next(current, current - 1) + True -> Done + } + }, + ) + + order.Lt -> + unfold( + from: start, + with: fn(current) { + case current > stop { + False -> Next(current, current + 1) + True -> Done + } + }, + ) } - - unfold(start, next_step) } fn do_find(continuation: fn() -> Action(a), f: fn(a) -> Bool) -> Result(a, Nil) { diff --git a/src/gleam/list.gleam b/src/gleam/list.gleam index 1a9d5ce..a46278a 100644 --- a/src/gleam/list.gleam +++ b/src/gleam/list.gleam @@ -1038,13 +1038,13 @@ pub fn sort(list: List(a), by compare: fn(a, a) -> Order) -> List(a) { /// /// ```gleam /// > range(0, 0) -/// [] +/// [0] /// /// > range(0, 5) -/// [0, 1, 2, 3, 4] +/// [0, 1, 2, 3, 4, 5] /// /// > range(1, -5) -/// [1, 0, -1, -2, -3, -4] +/// [1, 0, -1, -2, -3, -4, -5] /// ``` /// pub fn range(from start: Int, to stop: Int) -> List(Int) { @@ -1053,7 +1053,7 @@ pub fn range(from start: Int, to stop: Int) -> List(Int) { fn tail_recursive_range(start: Int, stop: Int, acc: List(Int)) -> List(Int) { case int.compare(start, stop) { - order.Eq -> reverse(acc) + order.Eq -> reverse([stop, ..acc]) order.Gt -> tail_recursive_range(start - 1, stop, [start, ..acc]) order.Lt -> tail_recursive_range(start + 1, stop, [start, ..acc]) } |