1use crate::prelude::*;
2
3#[derive(Debug, Clone)]
6pub enum List<T: Clone> {
7 Cons(T, Arc<List<T>>),
8 Nil,
9}
10
11impl<T: Clone> List<T> {
12 pub fn new() -> Self {
13 List::Nil
14 }
15
16 pub fn cons(self, t: T) -> Self {
17 List::Cons(t, Arc::new(self))
18 }
19
20 pub fn head(&self) -> Option<&T> {
21 match self {
22 List::Cons(t, _) => Some(t),
23 List::Nil => None,
24 }
25 }
26
27 pub fn tail(self) -> Option<Self> {
28 match self {
29 List::Cons(_, l) => Some((*l).clone()),
30 List::Nil => None,
31 }
32 }
33}
34
35impl<T: Clone> Default for List<T> {
36 fn default() -> Self {
37 Self::new()
38 }
39}
40
41#[derive(Debug, Clone)]
44pub struct Zipper<T: Clone> {
45 pub list: List<T>,
46 pub anti: List<T>,
47}
48
49impl<T: Clone> Zipper<T> {
50 pub fn new() -> Self {
51 Zipper {
52 list: List::new(),
53 anti: List::new(),
54 }
55 }
56
57 pub fn sing(t: T) -> Self {
58 Zipper::new().cons(t)
59 }
60
61 pub fn cons(self, t: T) -> Self {
62 Zipper {
63 list: self.list.cons(t),
64 anti: List::default(),
65 }
66 }
67
68 pub fn head(&self) -> Option<&T> {
69 self.list.head()
70 }
71
72 pub fn head_mut(&mut self) -> Option<&mut T> {
73 match &mut self.list {
74 List::Cons(t, _) => Some(t),
75 List::Nil => None,
76 }
77 }
78
79 pub fn tail(self) -> Option<Self> {
80 match self.list {
81 List::Cons(head, tail) => Some(Zipper {
82 list: (*tail).clone(),
83 anti: self.anti.cons(head),
84 }),
85 List::Nil => None,
86 }
87 }
88
89 pub fn anti_head(&self) -> Option<&T> {
90 self.anti.head()
91 }
92
93 pub fn back(self) -> Option<Self> {
94 match self.anti {
95 List::Cons(head, tail) => Some(Zipper {
96 list: self.list.cons(head),
97 anti: (*tail).clone(),
98 }),
99 List::Nil => None,
100 }
101 }
102}
103
104impl<T: Clone> Default for Zipper<T> {
105 fn default() -> Self {
106 Self::new()
107 }
108}
109
110impl Zipper<Box<str>> {
111 pub fn one(s: &str) -> Self {
112 Zipper::new().cons(s.into())
113 }
114}
115
116#[cfg(test)]
119mod tests {
120 use super::*;
121
122 #[test]
123 fn zipper() {
124 let mut z = Zipper::new();
125 z = z.cons(1);
126 assert_eq!(z.head().unwrap(), &1);
127 z = z.cons(2);
128 assert_eq!(z.head().unwrap(), &2);
129 z = z.cons(3);
130 assert_eq!(z.head().unwrap(), &3);
131 z = z.tail().unwrap();
132 assert_eq!(z.head().unwrap(), &2);
133 z = z.back().unwrap();
134 assert_eq!(z.head().unwrap(), &3);
135 }
136}