ConsList

Struct ConsList 

Source
pub struct ConsList<A>(/* private fields */);
Expand description

An immutable proper cons lists.

The cons list is perhaps the most basic immutable data structure: a singly linked list built out of ‘cons cells,’ which are cells containing two values, the left hand value being the head of the list and the right hand value being a reference to the rest of the list, or a Nil value denoting the end of the list.

Structure can be shared between lists (and is reference counted), and append to the front of a list is O(1). Cons cells keep track of the length of the list at the current position, as an extra optimisation, so getting the length of a list is also O(1). Otherwise, operations are generally O(n).

Implementations§

Source§

impl<A> ConsList<A>

Source

pub fn new() -> ConsList<A>

Construct an empty list.

Source

pub fn singleton<R>(v: R) -> ConsList<A>
where R: Shared<A>,

Construct a list with a single element.

Source

pub fn is_empty(&self) -> bool

Test whether a list is empty.

Time: O(1)

Source

pub fn cons<R>(&self, car: R) -> ConsList<A>
where R: Shared<A>,

Construct a list with a new value prepended to the front of the current list.

Time: O(1)

Source

pub fn head(&self) -> Option<Arc<A>>

Get the first element of a list.

If the list is empty, None is returned.

Time: O(1)

Source

pub fn tail(&self) -> Option<ConsList<A>>

Get the tail of a list.

The tail means all elements in the list after the first item (the head). If the list only has one element, the result is an empty list. If the list is empty, the result is None.

Time: O(1)

Source

pub fn uncons(&self) -> Option<(Arc<A>, ConsList<A>)>

Get the head and the tail of a list.

This function performs both the head function and the tail function in one go, returning a tuple of the head and the tail, or None if the list is empty.

§Examples

This can be useful when pattern matching your way through a list:

fn walk_through_list<A>(list: &ConsList<A>)
where A: Debug {
  match list.uncons() {
    None => (),
    Some((ref head, ref tail)) => {
      print!("{:?}", head);
      walk_through_list(tail)
    }
  }
}

Time: O(1)

Source

pub fn uncons2(&self) -> Option<(Arc<A>, Arc<A>, ConsList<A>)>

Get the two first elements and the tail of a list.

This function performs both the head function twice and the tail function in one go, returning a tuple of the double head and the tail, or None if the list is empty.

§Examples

This can be useful when pattern matching your way through a list:

fn walk_through_list<A>(list: &ConsList<A>)
where A: Debug {
  match list.uncons2() {
    None => (),
    Some((ref head, ref head2, ref tail)) => {
      print!("{:?} {:?}", head, head2);
      walk_through_list(tail)
    }
  }
}

Time: O(1)

Source

pub fn len(&self) -> usize

Get the length of a list.

This operation is instant, because cons cells store the length of the list they’re the head of.

Time: O(1)

§Examples
assert_eq!(5, conslist![1, 2, 3, 4, 5].len());
Source

pub fn append<R>(&self, right: R) -> Self
where R: Borrow<Self>,

Append the list right to the end of the current list.

Time: O(n)

§Examples
assert_eq!(conslist![1, 2, 3].append(conslist![7, 8, 9]), conslist![
  1, 2, 3, 7, 8, 9
]);
Source

pub fn reverse(&self) -> ConsList<A>

Construct a list which is the reverse of the current list.

Time: O(n)

§Examples
assert_eq!(conslist![1, 2, 3, 4, 5].reverse(), conslist![5, 4, 3, 2, 1]);
Source

pub fn iter(&self) -> Iter<A>

Get an iterator over a list.

Source

pub fn sort_by<F>(&self, cmp: F) -> ConsList<A>
where F: Fn(&A, &A) -> Ordering,

Sort a list using a comparator function.

Time: O(n log n)

Source

pub fn ptr_eq(&self, other: &Self) -> bool

Compare the Arc pointers of two ConsList

Source

pub fn insert<T>(&self, item: T) -> ConsList<A>
where A: Ord, T: Shared<A>,

Insert an item into a sorted list.

Constructs a new list with the new item inserted before the first item in the list which is larger than the new item, as determined by the Ord trait.

Time: O(n)

§Examples
assert_eq!(conslist![2, 4, 6].insert(5).insert(1).insert(3), conslist![
  1, 2, 3, 4, 5, 6
]);
Source

pub fn sort(&self) -> ConsList<A>
where A: Ord,

Sort a list.

Time: O(n log n)

§Examples
assert_eq!(
  conslist![2, 8, 1, 6, 3, 7, 5, 4].sort(),
  ConsList::from_iter(1..9)
);

Trait Implementations§

Source§

impl<'a, A> Add for &'a ConsList<A>

Source§

type Output = ConsList<A>

The resulting type after applying the + operator.
Source§

fn add(self, other: Self) -> Self::Output

Performs the + operation. Read more
Source§

impl<A> Add for ConsList<A>

Source§

type Output = ConsList<A>

The resulting type after applying the + operator.
Source§

fn add(self, other: Self) -> Self::Output

Performs the + operation. Read more
Source§

impl<A> Clone for ConsList<A>

Source§

fn clone(&self) -> Self

Clone a list.

Cons cells use Arc behind the scenes, so this is no more expensive than cloning an Arc reference.

Time: O(1)

1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<A> Debug for ConsList<A>
where A: Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<A> Default for ConsList<A>

Source§

fn default() -> Self

Default for lists is the empty list.

Source§

impl<'a, A, R> From<&'a [R]> for ConsList<A>
where &'a R: Shared<A>,

Source§

fn from(slice: &'a [R]) -> Self

Converts to this type from the input type.
Source§

impl<'a, A, R> From<&'a Vec<R>> for ConsList<A>
where &'a R: Shared<A>,

Source§

fn from(vec: &'a Vec<R>) -> Self

Converts to this type from the input type.
Source§

impl<A, R> From<Vec<R>> for ConsList<A>
where R: Shared<A>,

Source§

fn from(vec: Vec<R>) -> Self

Converts to this type from the input type.
Source§

impl<A, T> FromIterator<T> for ConsList<A>
where T: Shared<A>,

Source§

fn from_iter<I>(source: I) -> Self
where I: IntoIterator<Item = T>,

Creates a value from an iterator. Read more
Source§

impl<A> Hash for ConsList<A>
where A: Hash,

Source§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<A> IntoIterator for ConsList<A>

Source§

type IntoIter = Iter<A>

Which kind of iterator are we turning this into?
Source§

type Item = Arc<A>

The type of the elements being iterated over.
Source§

fn into_iter(self) -> Iter<A>

Creates an iterator from a value. Read more
Source§

impl<A> PartialEq for ConsList<A>
where A: PartialEq,

Source§

fn eq(&self, other: &ConsList<A>) -> bool

Test if two lists are equal.

This could potentially be an expensive operation, as we need to walk both lists to test for equality. We can very quickly determine equality if the lists have different lengths (can’t be equal). Otherwise, we walk the lists to compare values.

Time: O(n)

1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<A> Sum for ConsList<A>

Source§

fn sum<I>(it: I) -> Self
where I: Iterator<Item = Self>,

Takes an iterator and generates Self from the elements by “summing up” the items.
Source§

impl<A> Eq for ConsList<A>
where A: Eq,

Auto Trait Implementations§

§

impl<A> Freeze for ConsList<A>

§

impl<A> RefUnwindSafe for ConsList<A>
where A: RefUnwindSafe,

§

impl<A> Send for ConsList<A>
where A: Sync + Send,

§

impl<A> Sync for ConsList<A>
where A: Sync + Send,

§

impl<A> Unpin for ConsList<A>

§

impl<A> UnwindSafe for ConsList<A>
where A: RefUnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<A> Shared<A> for A

Source§

fn shared(self) -> Arc<A>

Get a new Arc pointer for this value
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.