You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
852 B

3 years ago
  1. package nova.monadic_sfx.util
  2. final class BoundedStack private (
  3. val underlying: List[Int],
  4. val maxSize: Int,
  5. val sp: Int
  6. ) {
  7. def push(v: Int): Either[String, BoundedStack] =
  8. if (sp < maxSize) Right(new BoundedStack(v :: underlying, maxSize, sp + 1))
  9. else Left("overflow")
  10. def pushAll(v: List[Int]) =
  11. if (sp + v.length < maxSize)
  12. Right(new BoundedStack(v ::: underlying, maxSize, sp + v.length))
  13. else Left("overflow")
  14. def pop =
  15. if (sp == 0) Left("Underflow")
  16. else
  17. Right(
  18. underlying(sp) -> new BoundedStack(
  19. underlying.splitAt(sp)._1,
  20. maxSize,
  21. sp - 1
  22. )
  23. )
  24. }
  25. object BoundedStack {
  26. def apply(
  27. // defaultValues: List[Int] = List.empty,
  28. maxSize: Int = 10
  29. // sp: Int = 0
  30. ) =
  31. new BoundedStack(List.empty, maxSize, 0)
  32. }