Class: Fr::SZipper::Node

Inherits:
Object show all
Defined in:
lib/fr/szipper/node.rb

Overview

Example implementation for a stream node. For the purposes of traversal with a zipper, nodes can be anything that implements #copy, #next, and #tail?

You’ll probably want access to some datum too, like #value. Otherwise you’ll be traversing a stream of otherwise useless cells.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, _next = nil) ⇒ Node

Returns a new instance of Node.



17
18
19
20
# File 'lib/fr/szipper/node.rb', line 17

def initialize(value, _next = nil)
  @value, @next =
    value, _next
end

Instance Attribute Details

#nextObject (readonly)

Returns the value of attribute next.



15
16
17
# File 'lib/fr/szipper/node.rb', line 15

def next
  @next
end

#valueObject (readonly)

Returns the value of attribute value.



13
14
15
# File 'lib/fr/szipper/node.rb', line 13

def value
  @value
end

Class Method Details

.build(enum) ⇒ Object

Convenient constructor to build a chain of Nodes from any “sequential” enum. That excludes things like Hash, Set, and Range because their traversal order isn’t deterministic. Otherwise, anything that implements #reverse and #inject can be converted.



53
54
55
56
57
58
59
60
61
62
63
# File 'lib/fr/szipper/node.rb', line 53

def build(enum)
  if enum.empty?
    raise Errors::ZipperError,
      "enum is empty"
  end

  tail, *rest = enum.reverse
  rest.inject(tail(tail)) do |_next, value|
    cons(value, _next)
  end
end

.cons(value, _next) ⇒ Object



38
39
40
# File 'lib/fr/szipper/node.rb', line 38

def cons(value, _next)
  Node.new(value, _next)
end

.tail(value) ⇒ Object



42
43
44
# File 'lib/fr/szipper/node.rb', line 42

def tail(value)
  Node.new(value)
end

Instance Method Details

#copy(options = {}) ⇒ Object



26
27
28
29
30
# File 'lib/fr/szipper/node.rb', line 26

def copy(options = {})
  Node.new \
    options.fetch(:value, @value),
    options.fetch(:next,  @next)
end

#inspectObject



32
33
34
# File 'lib/fr/szipper/node.rb', line 32

def inspect
  "Node(#{@value})"
end

#tail?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/fr/szipper/node.rb', line 22

def tail?
  @next.nil?
end