Class: Hamster::Cons

Inherits:
Object
  • Object
show all
Includes:
List
Defined in:
lib/hamster/list.rb

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

List::CADR

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#to_list

Constructor Details

#initialize(head, tail = EmptyList) ⇒ Cons

Returns a new instance of Cons.



1280
1281
1282
1283
1284
# File 'lib/hamster/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 Hamster::List

Instance Attribute Details

#headObject (readonly)

Returns the value of attribute head.



1278
1279
1280
# File 'lib/hamster/list.rb', line 1278

def head
  @head
end

#tailObject (readonly)

Returns the value of attribute tail.



1278
1279
1280
# File 'lib/hamster/list.rb', line 1278

def tail
  @tail
end

Instance Method Details

#cached_size?Boolean

Returns:

  • (Boolean)


1295
1296
1297
# File 'lib/hamster/list.rb', line 1295

def cached_size?
  @size != nil
end

#empty?Boolean

Returns:

  • (Boolean)


1286
1287
1288
# File 'lib/hamster/list.rb', line 1286

def empty?
  false
end

#sizeObject Also known as: length



1290
1291
1292
# File 'lib/hamster/list.rb', line 1290

def size
  @size ||= super
end