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
//! A list of nested pairs.
//!
//! The type [`List`] represents a Cons-style structure.
//! Every [`List`] is either [`Cons`] and contains a value and
//! another [`List`], or [`Nil`], which contains nothing.
#![warn(missing_docs)]
pub use List::{Cons, Nil};
/// An enum that represents a `Cons` list.
/// See [the module level documentation](self) for more.
#[derive(Debug, PartialEq, Eq, 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
}
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_val(5);
/// assert_eq!(x, Cons(5, Box::new(Nil)));
/// ```
#[inline]
pub fn new_val(x: T) -> List<T> {
Cons(x, Box::new(Nil))
}
/// Returns true if the List is a [`Cons`] value.
///
/// # Examples
/// ```
/// # use cons_rs::{List, Cons, Nil};
/// #
/// let x: List<i32> = Cons(5, Box::new(Nil));
/// 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> = Cons(5, Box::new(Nil));
/// 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()
}
/// 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::{Cons, Nil};
/// #
/// let x = Cons(5, Box::new(Nil));
/// assert_eq!(x.unwrap(), (5, Nil));
/// ```
///
/// ```should_panic
/// # use cons_rs::{List, Cons, 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) -> (T, List<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 = Cons(5, Box::new(Nil));
/// 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: (T, List<T>)) -> (T, List<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 = Cons(3, Box::new(Nil));
/// 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) -> (T, List<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 `Nil` (if self is [`Nil`]).
///
/// # Examples
///
/// ```
/// # use cons_rs::{List, Cons, Nil};
/// #
/// let x = Cons("Hello World".to_string(), Box::new(Nil));
/// let x_len = x.map(|s| s.len());
/// assert_eq!(x_len, Cons(11, Box::new(Nil)));
///
/// 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
}
}
}
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 {
use std::collections::VecDeque;
let mut container = 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
}
}
}
#[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 unwrap() {
let x = Cons(2, Box::new(Nil));
assert_eq!(x.unwrap(), (2, Nil));
}
#[test]
#[should_panic]
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() {
let x: List<String> = Cons(String::from("Hello"), Box::new(Nil));
assert_eq!(x.map(|s| s.len()), List::new_val(5));
assert_eq!(Nil.map(|s: String| s.len()), Nil);
}
#[test]
fn new_val() {
let x = List::new_val(8);
assert_eq!(x, Cons(8, Box::new(Nil)));
}
#[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
}
}