Class: Immutable::Cons
Overview
The basic building block for constructing lists
A Cons, also known as a “cons cell”, has a “head” and a “tail”, where the head is an element in the list, and the tail is a reference to the rest of the list. This way a singly linked list can be constructed, with each ‘Cons` holding a single element and a pointer to the next `Cons`.
The last ‘Cons` instance in the chain has the EmptyList as its tail.
Constant Summary
Constants included from List
Instance Attribute Summary collapse
-
#head ⇒ Object
readonly
Returns the value of attribute head.
-
#tail ⇒ Object
readonly
Returns the value of attribute tail.
Instance Method Summary collapse
- #cached_size? ⇒ Boolean
- #empty? ⇒ Boolean
-
#initialize(head, tail = EmptyList) ⇒ Cons
constructor
A new instance of Cons.
- #size ⇒ Object (also: #length)
Methods included from List
#<<, [], #add, #append, #at, #break, #chunk, #clear, #combination, #cycle, #delete, #delete_at, #drop, #drop_while, #dup, #each, #each_chunk, empty, #eql?, #fill, #flat_map, #flatten, from_enum, #group_by, #hash, #indices, #init, #inits, #insert, #inspect, #intersperse, #last, #map, #merge, #merge_by, #partition, #permutation, #pop, #pretty_print, #respond_to?, #reverse, #rotate, #sample, #select, #slice, #sort, #sort_by, #span, #split_at, #subsequences, #tails, #take, #take_while, #to_list, #transpose, #union, #uniq, #zip
Methods included from Enumerable
#<=>, #==, #compact, #each_index, #grep, #grep_v, #group_by, #inspect, #join, #partition, #pretty_print, #product, #reject, #sort_by, #sum, #to_set
Methods included from Enumerable
Constructor Details
#initialize(head, tail = EmptyList) ⇒ Cons
Returns a new instance of Cons.
1280 1281 1282 1283 1284 |
# File 'lib/immutable/list.rb', line 1280 def initialize(head, tail = EmptyList) @head = head @tail = tail @size = tail.cached_size? ? tail.size + 1 : nil end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class Immutable::List
Instance Attribute Details
#head ⇒ Object (readonly)
Returns the value of attribute head.
1278 1279 1280 |
# File 'lib/immutable/list.rb', line 1278 def head @head end |
#tail ⇒ Object (readonly)
Returns the value of attribute tail.
1278 1279 1280 |
# File 'lib/immutable/list.rb', line 1278 def tail @tail end |
Instance Method Details
#cached_size? ⇒ Boolean
1295 1296 1297 |
# File 'lib/immutable/list.rb', line 1295 def cached_size? @size != nil end |
#empty? ⇒ Boolean
1286 1287 1288 |
# File 'lib/immutable/list.rb', line 1286 def empty? false end |
#size ⇒ Object Also known as: length
1290 1291 1292 |
# File 'lib/immutable/list.rb', line 1290 def size @size ||= super end |