1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! A list of nested pairs.
//! 
//! The type [`List`] represents an immutable singly linked list.
//! Every [`List`] is either [`Cons`] and contains a value and
//! another [`List`], or [`Nil`], which contains nothing.
#![no_std]
#![warn(missing_docs)]

extern crate alloc;
use alloc::boxed::Box;

pub use List::{Cons, Nil};

/// An enum that represents a `Cons` list.
/// See [the module level documentation](self) for more.
#[derive(Debug, PartialEq, Clone, Default)]
pub enum List<T> {
    /// A value of type `T`, and a Box containing another [`List`].
    Cons(T, Box<List<T>>),
    /// Nothing.
    #[default]
    Nil
}

/// An alias for the data contained by a [`Cons`],
/// `(T, List<T>)`.
pub type ConsData<T> = (T, List<T>);

impl<T> List<T> {
    /// Returns a new [`Cons`] where `x` is the only value
    /// in the [`List`].
    ///
    /// This is equivalent to `Cons(x, Box::new(Nil))`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// let x = List::new(5);
    /// assert_eq!(x, Cons(5, Box::new(Nil)));
    /// ```
    #[inline]
    pub fn new(x: T) -> List<T> {
        Cons(x, Box::new(Nil))
    }
    
    /// Returns a new [`Cons`] where `x` is the only value
    /// in the [`List`].
    ///
    /// This is equivalent to `Cons(x, Box::new(Nil))`.
    #[inline]
    #[deprecated(
        since = "0.3.1",
        note = "Use new() instead."
    )]
    pub fn new_val(x: T) -> List<T> {
        List::new(x)
    }

    /// Returns true if the List is a [`Cons`] value.
    ///
    /// # Examples
    /// ```
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// let x: List<i32> = List::new(5);
    /// assert_eq!(x.is_cons(), true);
    ///
    /// let x: List<i32> = Nil;
    /// assert_eq!(x.is_cons(), false);
    /// ```
    #[inline]
    pub const fn is_cons(&self) -> bool {
        matches!(self, Cons(_, _))
    }

    /// Returns true if the List is a [`Nil`] value.
    ///
    /// # Examples:
    /// ```
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// let x: List<i32> = List::new(5);
    /// assert_eq!(x.is_nil(), false);
    ///
    /// let x: List<i32> = Nil;
    /// assert_eq!(x.is_nil(), true);
    /// ```
    #[inline]
    pub const fn is_nil(&self) -> bool {
        !self.is_cons()
    }

    /// Converts from `&List<T>` to `List<&T>`. If `self` is [`Cons`],
    /// `next` is always `Nil`. To preserve `next`, use [`as_ref`].
    ///
    /// [`as_ref`]: List::as_ref
    #[deprecated(
        since = "0.3.1", 
        note = "Any usage of val_as_ref can be replaced with as_ref."
    )]
    pub fn val_as_ref(&self) -> List<&T> {
        match *self {
            Cons(ref val, _) => List::new(val),
            Nil => Nil
        }
    }

    /// Converts from `&List<T>` to `List<&T>`.
    pub fn as_ref(&self) -> List<&T> {
        match *self {
            Cons(ref val, ref next) => Cons(val, Box::new((**next).as_ref())),
            Nil => Nil
        }
    }

    /// Converts from `&mut List<T>` to `List<&mut T>`.
    pub fn as_mut(&mut self) -> List<&mut T> {
        match *self {
            Cons(ref mut val, ref mut next) => Cons(val, Box::new((**next).as_mut())),
            Nil => Nil
        }
    }

    /// Returns the [`Cons`] value and next [`List`], 
    /// consuming `self`.
    ///
    /// # Panics
    ///
    /// Panics if `self` is [`Nil`].
    ///
    /// # Examples
    /// ```
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// let x = List::new(5);
    /// assert_eq!(x.expect("foo"), (5, Nil));
    /// ```
    ///
    /// ```should_panic
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// let x: List<i32> = Nil;
    /// x.expect("foo"); // panics with "foo"
    /// ```
    #[inline]
    pub fn expect(self, msg: &str) -> ConsData<T> {
        match self {
            Cons(val, next) => (val, *next),
            Nil => panic!("{msg}")
        }
    }
    
    /// Returns the [`Cons`] value and next [`List`], 
    /// consuming `self`.
    ///
    /// Usage of this function is discouraged, as it may panic.
    /// Instead, prefer to use pattern matching, 
    /// [`unwrap_or`] or [`unwrap_or_default`].
    ///
    /// # Panics
    ///
    /// Panics if `self` is [`Nil`].
    ///
    /// # Examples
    /// ```
    /// # use cons_rs::{List, Nil};
    /// #
    /// let x = List::new(5);
    /// assert_eq!(x.unwrap(), (5, Nil));
    /// ```
    ///
    /// ```should_panic
    /// # use cons_rs::{List, Nil};
    /// #
    /// let x: List<i32> = Nil;
    /// assert_eq!(x.unwrap(), (5, Nil)); // fails
    /// ```
    ///
    /// [`unwrap_or`]: List::unwrap_or
    /// [`unwrap_or_default`]: List::unwrap_or_default
    #[inline]
    pub fn unwrap(self) -> ConsData<T> {
        match self {
            Cons(val, next) => (val, *next),
            Nil => panic!("Called List::unwrap() on a Nil value.")
        }
    }

    /// Returns the contained [`Cons`] value and [`List`],
    /// or a provided default.
    ///
    /// # Examples
    ///
    /// ```
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// let x = List::new(5);
    /// assert_eq!(x.unwrap_or((6, Nil)), (5, Nil));
    ///
    /// let x: List<i32> = Nil;
    /// assert_eq!(x.unwrap_or((6, Nil)), (6, Nil));
    /// ```
    #[inline]
    pub fn unwrap_or(self, default: ConsData<T>) -> ConsData<T> {
        match self {
            Cons(val, next) => (val, *next),
            Nil => default
        }
    }

    /// Returns the contained [`Cons`] value and [`List`], or a default.
    ///
    /// Consumes `self`, and if `self` is [`Cons`], returns the contained
    /// value and list, otherwise, returns the [default value] 
    /// for T and [`Nil`].
    ///
    /// # Examples
    /// ```
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// let x = List::new(3);
    /// assert_eq!(x.unwrap_or_default(), (3, Nil));
    ///
    /// let x: List<i32> = Nil;
    /// assert_eq!(x.unwrap_or_default(), (0, Nil));
    /// ```
    ///
    /// [default value]: Default::default
    #[inline]
    pub fn unwrap_or_default(self) -> ConsData<T> 
    where T: Default {
        match self {
            Cons(val, next) => (val, *next),
            Nil => (Default::default(), Nil)
        }
    }

    /// Maps [`List<T>`] to [`List<U>`] by applying a function to the contained value
    /// (if [`Cons`], discarding the `next` value), or if [`Nil`], returns [`Nil`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// let x = List::new("Hello World".to_string());
    /// let x_len = x.map(|s| s.len());
    /// assert_eq!(x_len, List::new_val(11));
    ///
    /// let x: List<String> = Nil;
    /// let x_len = x.map(|s| s.len());
    /// assert_eq!(x_len, Nil);
    /// ```
    pub fn map<U, F>(self, f: F) -> List<U>
    where F: FnOnce(T) -> U
    {
        match self {
            Cons(val, _) => Cons(f(val), Box::new(Nil)),
            Nil => Nil
        }
    }

    /// Maps [`List<T>`] to [`List<U>`] by applying a function to the contained value
    /// (if [`Cons`]), or returns [`Nil`] (if [`Nil`]).
    ///
    /// # Examples
    ///
    /// ```
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// // you can unpack with a pattern
    /// let f = |(x, list)| (x + 1, list);
    /// let x = List::new(5).map_next(f);
    /// assert_eq!(x, Cons(6, Box::new(Nil)));
    ///
    /// let x: List<i32> = Nil;
    /// assert_eq!(x.map_next(f), Nil);
    /// ```
    pub fn map_next<U, F>(self, f: F) -> List<U>
    where F: FnOnce(ConsData<T>) -> ConsData<U>
    {
        match self {
            Cons(val, next) => {
                let result = f((val, *next));
                Cons(result.0, Box::new(result.1))
            },
            Nil => Nil
        }
    }
}

impl<T: Clone> IntoIterator for List<T> {
    type Item = T;
    type IntoIter = ListIterator<T>;

    fn into_iter(self) -> Self::IntoIter {
        ListIterator::new(self)
    }
}

// if anyone reads this and knows how to make it better,
// please tell me. raise an issue on the repo
impl<T> FromIterator<T> for List<T> {
    fn from_iter<U: IntoIterator<Item = T>>(iter: U) -> Self {
        let mut container = alloc::collections::VecDeque::new();
        // have to use a loop to make it List<T> instead of T
        for item in iter {
            container.push_back(Cons(item, Box::new(Nil)));
        }
        let mut list: List<T> = Nil;
        while let Some(Cons(val, _)) = container.pop_back() {
            list = Cons(val, Box::new(list));
        }
        list
    }
}

/// An iterator over a `List<T>`.
/// 
/// It is created by the [`into_iter`] method on [`List<T>`].
///
/// [`into_iter`]: List::into_iter
pub struct ListIterator<T> {
    next: Box<List<T>>
}

impl<T> ListIterator<T> {
    fn new(list: List<T>) -> ListIterator<T> {
        ListIterator {
            next: Box::new(list)
        }
    }
}

impl<T: Clone> Iterator for ListIterator<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if let Cons(val, next) = &*self.next {
            let tmp = val.clone();
            self.next = next.clone();
            Some(tmp)
        } else {
            None
        }
    }
}

impl<T> List<&T> {
    /// Maps a `List<&T>` to a `List<T>` by copying the contents of the list.
    ///
    /// # Examples
    /// 
    /// ```
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// let x = 3;
    /// let list_x = List::new(&x);
    /// assert_eq!(list_x, List::new(&3));
    ///
    /// let copy_x = list_x.copied();
    /// assert_eq!(copy_x, List::new(3));
    /// ```
    pub fn copied(self) -> List<T> 
    where T: Copy {
        self.map(|x| *x)
    }

    /// Maps a `List<&T>` to a `List<T>` by cloning the contents of the list.
    ///
    /// # Examples
    /// 
    /// ```
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// let x = 3;
    /// let list_x = List::new(&x);
    /// assert_eq!(list_x, List::new(&3));
    ///
    /// let clone_x = list_x.cloned();
    /// assert_eq!(clone_x, List::new(3));
    /// ```
    pub fn cloned(self) -> List<T>
    where T: Clone {
        self.map(|x| x.clone())
    }
}

impl<T> List<&mut T> {
    /// Maps a `List<&mut T>` to a `List<T>` by copying the contents of the list.
    ///
    /// # Examples
    /// 
    /// ```
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// let mut x = 3;
    /// let list_x = List::new(&mut x);
    /// assert_eq!(list_x, List::new(&mut 3));
    ///
    /// let copy_x = list_x.copied();
    /// assert_eq!(copy_x, List::new(3));
    /// ```
    pub fn copied(self) -> List<T> 
    where T: Copy {
        self.map(|x| *x)
    }

    /// Maps a `List<&mut T>` to a `List<T>` by cloning the contents of the list.
    ///
    /// # Examples
    /// 
    /// ```
    /// # use cons_rs::{List, Cons, Nil};
    /// #
    /// let mut x = 3;
    /// let list_x = List::new(&mut x);
    /// assert_eq!(list_x, List::new(&mut 3));
    ///
    /// let clone_x = list_x.cloned();
    /// assert_eq!(clone_x, List::new(3));
    /// ```
    pub fn cloned(self) -> List<T>
    where T: Clone {
        self.map(|x| x.clone())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn is_cons() {
        let list = Cons(3, Box::new(Nil));
        assert!(list.is_cons());
        assert!(!list.is_nil());
    }

    #[test]
    fn is_nil() {
        let list: List<i32> = Nil;
        assert!(list.is_nil());
        assert!(!list.is_cons());
    }

    #[test]
    fn expect() {
        let x = List::new(5);
        assert_eq!(x.expect("foo"), (5, Nil));
    }

    #[test]
    #[should_panic(expected = "foobar")]
    fn expect_panic() {
        let x: List<i32> = Nil;
        x.expect("foobar");
    }
    
    #[test]
    fn unwrap() {
        let x = Cons(2, Box::new(Nil));
        assert_eq!(x.unwrap(), (2, Nil));
    }

    #[test]
    #[should_panic(expected = "List::unwrap")]
    fn unwrap_panic() {
        let x: List<u32> = Nil;
        x.unwrap(); // panics
    }

    #[test]
    fn unwrap_or() {
        let x: List<u32> = Nil;
        assert_eq!(x.unwrap_or((3, Nil)), (3, Nil));
    }

    #[test]
    fn unwrap_or_default() {
        let x: List<u32> = Nil;
        assert_eq!(x.unwrap_or_default(), (0, Nil));
    }

    #[test]
    fn map() {
        use alloc::string::String;
        let x: List<String> = Cons(String::from("Hello"), Box::new(Nil));
        assert_eq!(x.map(|s| s.len()), List::new(5));
        assert_eq!(Nil.map(|s: String| s.len()), Nil);
    }

    #[test]
    fn map_next() {
        let f = |(x, y)| (x + 1, y);
        let x = Cons(2, Box::new(List::new(3)));
        assert_eq!(x.map_next(f), Cons(3, Box::new(List::new(3))));
        assert_eq!(Nil.map_next(f), Nil);
    }

    #[test]
    fn as_ref() {
        use alloc::string::ToString;
        let x = Cons("air".to_string(), Box::new(List::new("hello".to_string())));
        assert_eq!(x.as_ref(), Cons(&"air".to_string(), Box::new(List::new(&"hello".to_string()))));
    }

    #[test]
    fn as_mut() {
        let mut x = List::new(6);
        assert_eq!(x.as_mut(), List::new(&mut 6));
    }

    #[test]
    fn cl_ref() {
        let x = List::new(&4);
        assert_eq!(x.cloned(), List::new(4));
    }

    #[test]
    fn cp_ref() {
        let x = List::new(&4);
        assert_eq!(x.copied(), List::new(4));
    }

    #[test]
    fn cl_mut() {
        let mut v = 4;
        let x = List::new(&mut v);
        assert_eq!(x.cloned(), List::new(v));
    }

    #[test]
    fn cp_mut() {
        let mut v = 4;
        let x = List::new(&mut v);
        assert_eq!(x.copied(), List::new(v));
    }
    
    #[test]
    fn iter() {
        let list = Cons(2, Box::new(Cons(4, Box::new(Nil))));
        let mut iterator = list.into_iter();
        assert_eq!(iterator.next(), Some(2));
        assert_eq!(iterator.next(), Some(4));
        assert_eq!(iterator.next(), None);
    }

    #[test]
    fn iter_loop() {
        let list = Cons(0, Box::new(Cons(2, Box::new(Cons(4, Box::new(Nil))))));
        for (i, val) in list.into_iter().enumerate() {
            assert_eq!(val, i * 2);
        }
    }

    #[test]
    fn for_loop() {
        let list = Cons(0, Box::new(Cons(1, Box::new(Cons(2, Box::new(Nil))))));
        let mut i = 0;
        for val in list {
            assert_eq!(val, i);
            i += 1;
        }
    }

    #[test]
    fn from_iter() {
        let list: List<_> = List::from_iter(1..=5);

        assert_eq!(list, 
                  Cons(1, Box::new(
                      Cons(2, Box::new(
                          Cons(3, Box::new(
                              Cons(4, Box::new(
                                  Cons(5, Box::new(Nil))
                              ))
                          ))
                      ))
                  )));
                // that was 11 close-parens in a row
    }
}