diff --git a/src/fortheck/stack.gleam b/src/fortheck/stack.gleam index 321b679..69bedf7 100644 --- a/src/fortheck/stack.gleam +++ b/src/fortheck/stack.gleam @@ -12,7 +12,7 @@ pub fn new() -> Stack(a) { } pub fn from_list(list: List(a)) -> Result(Stack(a), Error) { - list.try_fold(over: list, from: new(), with: push) + push_items(onto: new(), this: list) } pub fn to_list(stack: Stack(a)) -> List(a) { @@ -28,6 +28,13 @@ pub fn push(onto stack: Stack(a), this item: a) -> Result(Stack(a), Error) { Ok(Stack(..stack, length: stack.length + 1, data: [item, ..stack.data])) } +pub fn push_items( + onto stack: Stack(a), + this items: List(a), +) -> Result(Stack(a), Error) { + list.try_fold(over: items, from: stack, with: push) +} + pub fn pop(from stack: Stack(a)) -> Result(#(a, Stack(a)), Error) { case stack.data { [] -> Error(StackUnderflow) @@ -35,18 +42,9 @@ pub fn pop(from stack: Stack(a)) -> Result(#(a, Stack(a)), Error) { } } -pub fn try_pop( - from stack: Stack(a), - apply fun: fn(a, Stack(a)) -> Result(b, Error), -) -> Result(b, Error) { - use #(item, stack) <- result.try(pop(from: stack)) - - fun(item, stack) -} - pub fn pop_2(from stack: Stack(a)) -> Result(#(#(a, a), Stack(a)), Error) { - use b, stack <- try_pop(from: stack) - use a, stack <- try_pop(from: stack) + use #(b, stack) <- result.try(pop(from: stack)) + use #(a, stack) <- result.try(pop(from: stack)) Ok(#(#(a, b), stack)) } diff --git a/test/stack_test.gleam b/test/fortheck/stack_test.gleam similarity index 86% rename from test/stack_test.gleam rename to test/fortheck/stack_test.gleam index f80dcab..a17a552 100644 --- a/test/stack_test.gleam +++ b/test/fortheck/stack_test.gleam @@ -58,13 +58,6 @@ pub fn pop_test() { |> should.be_ok |> pair.first |> should.equal(3) - - { - use a, _ <- stack.try_pop(stack) - Ok(a) - } - |> should.be_ok - |> should.equal(3) } pub fn pop_2_test() { @@ -75,13 +68,6 @@ pub fn pop_2_test() { |> should.be_ok |> pair.first |> should.equal(#(2, 3)) - - { - use a, b, _ <- stack.try_pop_2(stack) - Ok(#(a, b)) - } - |> should.be_ok - |> should.equal(#(2, 3)) } pub fn pop_2_stack_underflow_test() {