Module: Apricot::Seq

Includes:
Comparable, Enumerable
Included in:
Cons, List, Array::Seq, Range::Seq
Defined in:
lib/apricot/seq.rb

Overview

Every seq should include this module and define ‘first’ and ‘next’ methods. A seq may redefine ‘rest’ and ‘each’ if there is a more efficient way to implement them.

‘first’ should return the first item in the seq. ‘next’ should return a seq of the rest of the items in the seq, or nil

if there are no more items.

Instance Method Summary collapse

Methods included from Enumerable

#to_list

Instance Method Details

#<=>(other) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/apricot/seq.rb', line 50

def <=>(other)
  return unless other.is_a?(Seq) || other.nil?
  s, o = self, other

  while s && o
    comp = s.first <=> o.first
    return comp unless comp == 0
    s = s.next
    o = o.next
  end

  if s
    1
  elsif o
    -1
  else
    0
  end
end

#cons(x) ⇒ Object



46
47
48
# File 'lib/apricot/seq.rb', line 46

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

#eachObject



17
18
19
20
21
22
23
24
25
26
# File 'lib/apricot/seq.rb', line 17

def each
  s = self

  while s
    yield s.first
    s = s.next
  end

  self
end

#empty?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/apricot/seq.rb', line 32

def empty?
  false
end

#hashObject



72
73
74
75
# File 'lib/apricot/seq.rb', line 72

def hash
  hashes = map {|x| x.hash }
  hashes.reduce(hashes.size) {|acc,hash| acc ^ hash }
end

#lastObject



36
37
38
39
40
41
42
43
44
# File 'lib/apricot/seq.rb', line 36

def last
  s = self

  while s.next
    s = s.next
  end

  s.first
end

#restObject



13
14
15
# File 'lib/apricot/seq.rb', line 13

def rest
  self.next || List::EMPTY_LIST
end

#to_sObject Also known as: inspect



77
78
79
80
81
82
# File 'lib/apricot/seq.rb', line 77

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

#to_seqObject



28
29
30
# File 'lib/apricot/seq.rb', line 28

def to_seq
  self
end