Class: Apricot::List

Inherits:
Object show all
Includes:
Seq
Defined in:
lib/apricot/list.rb

Overview

A linked list implementation representing (a b c) syntax in Apricot

Direct Known Subclasses

EmptyList

Defined Under Namespace

Classes: EmptyList

Constant Summary collapse

EMPTY_LIST =
EmptyList.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Seq

#<=>, #each, #empty?, #hash, #last, #rest

Constructor Details

#initialize(head, tail) ⇒ List

Returns a new instance of List.



16
17
18
19
20
# File 'lib/apricot/list.rb', line 16

def initialize(head, tail)
  @head = head
  @tail = tail || EMPTY_LIST
  @count = tail ? tail.count + 1 : 1
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



14
15
16
# File 'lib/apricot/list.rb', line 14

def count
  @count
end

#headObject (readonly)

Returns the value of attribute head.



14
15
16
# File 'lib/apricot/list.rb', line 14

def head
  @head
end

#tailObject (readonly)

Returns the value of attribute tail.



14
15
16
# File 'lib/apricot/list.rb', line 14

def tail
  @tail
end

Class Method Details

.[](*args) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/apricot/list.rb', line 6

def self.[](*args)
  list = EMPTY_LIST
  args.reverse_each do |arg|
    list = list.cons(arg)
  end
  list
end

Instance Method Details

#cons(x) ⇒ Object



22
23
24
# File 'lib/apricot/list.rb', line 22

def cons(x)
  List.new(x, self)
end

#firstObject



37
38
39
# File 'lib/apricot/list.rb', line 37

def first
  @head
end

#inspectObject Also known as: to_s



49
50
51
52
53
54
55
56
# File 'lib/apricot/list.rb', line 49

def inspect
  return '()' if empty?

  str = '('
  each {|x| str << x.apricot_inspect << ' ' }
  str.chop!
  str << ')'
end

#nextObject



41
42
43
# File 'lib/apricot/list.rb', line 41

def next
  @tail.empty? ? nil : @tail
end

#to_listObject



33
34
35
# File 'lib/apricot/list.rb', line 33

def to_list
  self
end

#to_seqObject



45
46
47
# File 'lib/apricot/list.rb', line 45

def to_seq
  self
end