refactor: straighten stack
This commit is contained in:
parent
1e6773ac28
commit
2b83aea200
2 changed files with 10 additions and 26 deletions
|
@ -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))
|
||||
}
|
||||
|
|
|
@ -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() {
|
Loading…
Reference in a new issue