refactor: straighten stack - part III
This commit is contained in:
parent
f84d6fdc85
commit
4587bee699
1 changed files with 12 additions and 23 deletions
|
@ -1,6 +1,5 @@
|
|||
import gleam/bool
|
||||
import gleam/list
|
||||
import gleam/result
|
||||
import gleam/list.{reverse, try_fold}
|
||||
import gleam/result.{then, try}
|
||||
|
||||
pub type Error {
|
||||
StackOverflow
|
||||
|
@ -12,7 +11,7 @@ pub opaque type Stack(a) {
|
|||
}
|
||||
|
||||
pub fn new() -> Stack(a) {
|
||||
Stack(131_072, 0, [])
|
||||
Stack(capacity: 131_072, length: 0, data: [])
|
||||
}
|
||||
|
||||
pub fn from_list(list: List(a)) -> Result(Stack(a), Error) {
|
||||
|
@ -20,23 +19,22 @@ pub fn from_list(list: List(a)) -> Result(Stack(a), Error) {
|
|||
}
|
||||
|
||||
pub fn to_list(stack: Stack(a)) -> List(a) {
|
||||
list.reverse(stack.data)
|
||||
reverse(stack.data)
|
||||
}
|
||||
|
||||
pub fn push(onto stack: Stack(a), this item: a) -> Result(Stack(a), Error) {
|
||||
use <- bool.guard(
|
||||
when: stack.length >= stack.capacity,
|
||||
return: Error(StackOverflow),
|
||||
)
|
||||
|
||||
case stack.length < stack.capacity {
|
||||
True ->
|
||||
Ok(Stack(..stack, length: stack.length + 1, data: [item, ..stack.data]))
|
||||
False -> Error(StackOverflow)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
try_fold(over: items, from: stack, with: push)
|
||||
}
|
||||
|
||||
pub fn pop(from stack: Stack(a)) -> Result(#(a, Stack(a)), Error) {
|
||||
|
@ -47,17 +45,8 @@ pub fn pop(from stack: Stack(a)) -> Result(#(a, Stack(a)), Error) {
|
|||
}
|
||||
|
||||
pub fn pop_2(from stack: Stack(a)) -> Result(#(#(a, a), Stack(a)), Error) {
|
||||
use #(b, stack) <- result.try(pop(from: stack))
|
||||
use #(a, stack) <- result.try(pop(from: stack))
|
||||
use #(b, stack) <- try(pop(from: stack))
|
||||
use #(a, stack) <- then(pop(from: stack))
|
||||
|
||||
Ok(#(#(a, b), stack))
|
||||
}
|
||||
|
||||
pub fn try_pop_2(
|
||||
from stack: Stack(a),
|
||||
apply fun: fn(a, a, Stack(a)) -> Result(b, Error),
|
||||
) -> Result(b, Error) {
|
||||
use #(#(a, b), stack) <- result.try(pop_2(from: stack))
|
||||
|
||||
fun(a, b, stack)
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue