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.

79 lines
1.9 KiB

3 years ago
3 years ago
3 years ago
  1. package nova.monadic_sfx.util
  2. import com.softwaremill.quicklens._
  3. final class MutHistory[T](initValue: T) {
  4. private var _values = Vector(initValue)
  5. def values = _values
  6. private var _sp = 0
  7. def sp = _sp
  8. // def current = if (ints.isEmpty) None else Some(ints(sp))
  9. def current = _values(_sp)
  10. def push(v: T) = {
  11. if (_sp < _values.length - 1) {
  12. _values = _values.splitAt(_sp)._1
  13. _values = _values :+ v
  14. } else {
  15. _values = _values :+ v
  16. _sp = _values.length - 1
  17. }
  18. }
  19. def forward() = {
  20. if (!_values.isEmpty && _sp < _values.length - 1) _sp += 1
  21. }
  22. def backward() = {
  23. if (_sp > 0) {
  24. _sp -= 1
  25. }
  26. }
  27. }
  28. final class History[T] private (val state: History.State[T]) {
  29. def current = state.values(state.sp)
  30. def push(v: T) = {
  31. val nextState =
  32. // state.copy(state.values.splitAt(state.sp)._1 :+ v, state.sp + 1)
  33. if (state.sp < state.values.length - 1) {
  34. state.modify(_.values).using(_.splitAt(state.sp)._1 :+ v)
  35. } else {
  36. val s1 = state
  37. .modify(_.values)
  38. .using(_ :+ v)
  39. s1.modify(_.sp)
  40. .setTo(s1.values.length - 1)
  41. }
  42. new History(nextState)
  43. }
  44. def forward = {
  45. // val nextState =
  46. if (!state.values.isEmpty && state.sp < state.values.length - 1)
  47. new History(state.modify(_.sp).using(_ + 1))
  48. else this
  49. // new History(nextState)
  50. }
  51. def backward = {
  52. // val nextState =
  53. if (state.sp > 0) new History(state.modify(_.sp).using(_ - 1)) else this
  54. // new History(nextState)
  55. }
  56. }
  57. // final class HistoryImpl()
  58. object History {
  59. case class State[T](values: Vector[T], sp: Int)
  60. def apply[T](intialValue: T) =
  61. new History(State(Vector(intialValue), 0))
  62. // val history = new History(History.State(Vector.empty, 0))
  63. implicit class HistoryOps[T](private val h: History[T]) extends AnyVal {
  64. def :+(v: T) = h.push(v)
  65. }
  66. }
  67. // History.history.push(1).forward