metaractor-sycamore 0.4.1

Sign up to get free protection for your applications and to get access to all the features.
data/README.md ADDED
@@ -0,0 +1,571 @@
1
+
2
+ # Sycamore
3
+
4
+ > _"The Egyptians' Holy Sycamore also stood on the threshold of life and death, connecting the two worlds."_
5
+ > -- [Wikipedia: Tree of Life](http://en.wikipedia.org/wiki/Tree_of_life)
6
+
7
+ [![Gem Version](https://badge.fury.io/rb/sycamore.svg)](http://badge.fury.io/rb/sycamore)
8
+ [![Travis CI Build Status](https://secure.travis-ci.org/marcelotto/sycamore.png)](https://travis-ci.org/marcelotto/sycamore?branch=master)
9
+ [![Coverage Status](https://coveralls.io/repos/marcelotto/sycamore/badge.png)](https://coveralls.io/r/marcelotto/sycamore)
10
+ [![Inline docs](http://inch-ci.org/github/marcelotto/sycamore.png)](http://inch-ci.org/github/marcelotto/sycamore)
11
+ [![Documentation](http://img.shields.io/badge/docs-rdoc.info-blue.svg)](http://rubydoc.org/gems/sycamore/frames)
12
+ [![Gitter Chat](http://img.shields.io/badge/chat-gitter.im-orange.svg)](https://gitter.im/marcelotto/sycamore)
13
+ [![License](http://img.shields.io/license/MIT.png?color=green)](http://opensource.org/licenses/MIT)
14
+
15
+ **Sycamore is an implementation of an unordered tree data structure.**
16
+
17
+ Features:
18
+
19
+ - easy, hassle-free access to arbitrarily deep nested elements
20
+ - grows automatically when needed
21
+ - familiar Hash interface
22
+ - no more `nil`-induced errors
23
+
24
+ Imagine a Sycamore tree as a recursively nested set. The elements of this set, called nodes, are associated with a child tree of additional nodes and so on. This might be different to your usual understanding of a tree, which has to have one single root node, but this notion is much more general. The usual tree is just a special case with just one node at the first level. But I prefer to think of the root to be implicit. Effectively every object is a tree in this sense. You can assume `self` to be the implicit root.
25
+
26
+ Restrictions:
27
+
28
+ - Only values you would use as keys of a hash should be used as nodes of a Sycamore tree. Although Ruby's official Hash documentation says *a Hash allows you to use any object type*, one is well advised [to use immutable objects only](http://jafrog.com/2012/10/07/mutable-objects-as-hash-keys-in-ruby.html). Enumerables as nodes are explicitly excluded by Sycamore.
29
+ - The nodes are unordered and can't contain duplicates.
30
+ - A Sycamore tree is uni-directional, i.e. has no relationship to its parent.
31
+
32
+ ## Why
33
+
34
+ Trees in the sense of recursively nested sets are omnipresent today. But why then are there so few implementations of tree data structures? The answer is simple: because of Ruby's powerful built-in hashes. The problem is that while Ruby's Hash, as an implementation of the [Hash map data structure](https://en.wikipedia.org/wiki/Hash_table), might be perfectly fine for flat dictionary like structures, it is not very well-suited for storing tree structures. Ruby's hash literals, which allow it to easily nest multiple hashes, belie this fact. But it catches up when you want to build up a tree with hashes dynamically and have to manage the hash nesting manually.
35
+
36
+ In contrast to the few existing implementations of tree data structures in Ruby, Sycamores is based on Ruby's very efficient hashes and contains the values directly without any additional overhead. It only wraps the hashes itself. This wrapper object is very thin, containing nothing more than the hash itself. This comes at the price of the aforementioned restrictions, prohibiting it to be a general applicable tree implementation.
37
+
38
+ Another compelling reason for the use of Sycamore is its handling of `nil`. Much has [been](https://www.youtube.com/watch?v=OMPfEXIlTVE) [said](http://programmers.stackexchange.com/questions/12777/are-null-references-really-a-bad-thing) about the problem of `nil` (or equivalent null-values in other languages), including: ["It was my Billion-dollar mistake"](http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare) from its founder, Tony Hoare. Every developer has experienced it in the form of errors such as
39
+
40
+ ```
41
+ NoMethodError: undefined method '[]' for nil:NilClass
42
+ ```
43
+
44
+ With Sycamore this is a thing of the past.
45
+
46
+
47
+ ## Supported Ruby versions
48
+
49
+ - MRI >= 2.1
50
+ - JRuby
51
+ - Rubinius
52
+
53
+
54
+ ## Dependencies
55
+
56
+ - none
57
+
58
+ ## Installation
59
+
60
+ The recommended installation method is via [RubyGems](http://rubygems.org/).
61
+
62
+ $ gem install sycamore
63
+
64
+
65
+ ## Usage
66
+
67
+ I will introduce Sycamore's Tree API by comparing it with [Ruby's Hash API](http://ruby-doc.org/core-2.2.3/Hash.html).
68
+
69
+ In the following I'll always write `Tree` for the Sycamore tree class, instead of the fully qualified `Sycamore::Tree`. By default, this global `Tree` constant is not available. If you want this, you'll have to
70
+
71
+ ```ruby
72
+ require 'sycamore/extension'
73
+ ```
74
+
75
+ When you can't or don't to want to have the `Tree` alias constant in the global namespace, but still want a short alternative name, you can alternatively
76
+
77
+ ```ruby
78
+ require 'sycamore/stree'
79
+ ```
80
+
81
+ to get an alias constant `STree` with less potential for conflicts.
82
+
83
+ I recommend trying the following code yourself in a Ruby REPL like [Pry](http://pryrepl.org).
84
+
85
+
86
+ ### Creating trees
87
+
88
+ A `Sycamore::Tree` can be created similar to Hashes with the standard constructor or the class-level `[]` operator.
89
+
90
+ `Tree.new` creates an empty `Sycamore::Tree`.
91
+
92
+ ```ruby
93
+ tree = Tree.new
94
+ tree.empty? # => true
95
+ ```
96
+
97
+ No additional arguments are supported at the time. As you'll see, for a `Sycamore::Tree` the functionality of the Hash constructor to specify the default value behaviour is of too little value to justify its use in the default constructor, so I'd like to reserve them for something more useful.
98
+
99
+ The `[]` operator creates a new `Tree` and adds the arguments as its initial input. It can handle a single node value, a collection of nodes or a complete tree.
100
+
101
+ ```ruby
102
+ Tree[1] # => #<Sycamore::Tree:0x3fcfe51a5a3c {1=>n/a}>
103
+ Tree[1, 2, 3] # => #<Sycamore::Tree:0x3fcfe51a56f4 {1=>n/a, 2=>n/a, 3=>n/a}>
104
+ Tree[1, 2, 2, 3] # => #<Sycamore::Tree:0x3fcfe51a52d0 {1=>n/a, 2=>n/a, 3=>n/a}>
105
+ Tree[x: 1, y: 2] # => #<Sycamore::Tree:0x3fcfe51a4e34 {:x=>1, :y=>2}>
106
+ ```
107
+
108
+ As you can see in line 3 nodes are stored as a set, i.e. with duplicates removed.
109
+
110
+ Note that multiple arguments are not interpreted as an associative array as `Hash[]` does, but rather as a set of leaves, i.e. nodes without children.
111
+
112
+ ```ruby
113
+ Hash[1, 2, 3, 4] # => {1=>2, 3=>4}
114
+ Hash[1, 2, 3] # => ArgumentError: odd number of arguments for Hash
115
+ ```
116
+
117
+ You can also see that children of leaves, i.e. nodes without children, are signified with `n/a`. When providing input data with Hashes, you can use `nil` as the child value of a leaf.
118
+
119
+ ```ruby
120
+ Tree[x: 1, y: 2, z: nil]
121
+ # => #<Sycamore::Tree:0x3fcfe51a4e34 {:x=>1, :y=>2, :z=>n/a}>
122
+ ```
123
+
124
+ In general the `nil` child value for leaves in Hash literals is mandatory, but on the first level it can be ommitted, by providing the leaves as an argument before the non-leaf nodes.
125
+
126
+ ```ruby
127
+ Tree[:a, :b, c: {d: 1, e: nil}]
128
+ # => #<Sycamore::Tree:0x3fd3f9c6bb0c {:a=>n/a, :b=>n/a, :c=>{:d=>1, :e=>n/a}}>
129
+ ```
130
+
131
+ If you really want to have a node with `nil` as a child, you'll have to put the `nil` in an array.
132
+
133
+ ```ruby
134
+ Tree[x: 1, y: 2, z: [nil]]
135
+ # => #<Sycamore::Tree:0x3fd641858264 {:x=>1, :y=>2, :z=>nil}>
136
+ ```
137
+
138
+
139
+ ### Accessing trees
140
+
141
+ Access to elements of a `Sycamore::Tree` is mostly API-compatible to that of Rubys Hash class. But there is one major difference in the return type of most of the access methods: Since we are dealing with a recursively defined tree structure, the returned children are always trees as well.
142
+
143
+ The main method for accessing a tree is the `[]` operator.
144
+
145
+ ```ruby
146
+ tree = Tree[x: 1, y: {2 => "a"}]
147
+
148
+ tree[:x] # => #<Sycamore::Tree:0x3fea48d24d40 {1=>n/a}>
149
+ tree[:y] # => #<Sycamore::Tree:0x3fea48d24b74 {2=>"a"}>
150
+ tree[:y][2] # => #<Sycamore::Tree:0x3fea48d248f4 {"a"=>n/a}>
151
+ ```
152
+
153
+ The actual nodes of a tree can be retrieved with the method `nodes`.
154
+
155
+ ```ruby
156
+ tree.nodes # => [:x, :y]
157
+ tree[:x].nodes # => [1]
158
+ tree[:y].nodes # => [2]
159
+ tree[:y][2].nodes # => ["a"]
160
+ ```
161
+
162
+ If it's certain that a tree has at most one element, you can also use `node` to get that node directly.
163
+
164
+ ```ruby
165
+ tree[:y].node # => 2
166
+ tree[:y][2].node # => "a"
167
+ tree[:x][1].node # => nil
168
+ tree.node # Sycamore::NonUniqueNodeSet: multiple nodes present: [:x, :y]
169
+ ```
170
+
171
+ The bang variant `node!` raises an error when the node set is empty, instead of returning `nil`.
172
+
173
+ ```ruby
174
+ tree[:y][2].node! # => "a"
175
+ tree[:x][1].node! # => # Sycamore::EmptyNodeSet: no node present
176
+ ```
177
+
178
+ As opposed to Hash, the `[]` operator of `Sycamore::Tree` also supports multiple arguments which get interpreted as a path.
179
+
180
+ ```ruby
181
+ tree[:y, 2].node # => "a"
182
+ ```
183
+
184
+ For compatibility with Ruby 2.3 Hashes, this can also be done with the `dig` method.
185
+
186
+ ```ruby
187
+ tree.dig(:y, 2).node # => "a"
188
+ ```
189
+
190
+ `fetch`, as a more controlled way to access the elements, is also supported.
191
+
192
+ ```ruby
193
+ tree.fetch(:x) # => #<Sycamore::Tree:0x3fea48d24d40 {1=>n/a}>
194
+ tree.fetch(:z) # => KeyError: key not found: :z
195
+ tree.fetch(:z, :default) # => :default
196
+ tree.fetch(:z) { :default } # => :default
197
+ ```
198
+
199
+ Fetching the child of a leaf behaves almost the same as fetching the child of a non-existing node, i.e. the default value is returned or a `KeyError` gets raised. In order to differentiate these cases, a `Sycamore::ChildError` as a subclass of `KeyError` is raised when accessing the child of a leaf.
200
+
201
+ `fetch_path` allows a `dig` similar access with `fetch` semantics, except it requires the path of nodes to be given as an Enumerable.
202
+
203
+ ```ruby
204
+ tree.fetch_path([:y, 2]).node # => "a"
205
+ tree.fetch_path([:y, 3]) # => KeyError: key not found: 3
206
+ tree.fetch_path([:y, 3], :default) # => :default
207
+ tree.fetch_path([:y, 3]) { :default } # => :default
208
+ ```
209
+
210
+ The number of nodes of a tree can be determined with `size`. This will only count direct nodes.
211
+
212
+ ```ruby
213
+ tree.size # => 2
214
+ ```
215
+
216
+ `total_size` or its short alias `tsize` returns the total number of nodes of a tree, including the nodes of children.
217
+
218
+ ```ruby
219
+ tree.total_size # => 5
220
+ tree[:y].tsize # => 2
221
+ ```
222
+
223
+ The height of a tree, i.e. the length of its longest path can be computed with the method `height`.
224
+
225
+ ```ruby
226
+ tree.height # => 3
227
+ ```
228
+
229
+ `empty?` checks if a tree is empty.
230
+
231
+ ```ruby
232
+ tree.empty? # => false
233
+ tree[:x, 1].empty? # => true
234
+ ```
235
+
236
+ `leaf?` checks if a node is a leaf.
237
+
238
+ ```ruby
239
+ tree.leaf? :x # => false
240
+ tree[:x].leaf? 1 # => true
241
+ ```
242
+
243
+ `leaves?` (or one of its aliases `external?` and `flat?`) can be used to determine this for more nodes at once.
244
+
245
+ ```ruby
246
+ Tree[1, 2, 3].leaves?(1, 2) # => true
247
+ ```
248
+
249
+ Without any arguments `leaves?` returns whether all nodes of a tree are leaves.
250
+
251
+ ```ruby
252
+ Tree[1, 2].leaves? # => true
253
+ ```
254
+
255
+ `include?` checks whether one or more nodes are in the set of nodes of this tree.
256
+
257
+ ```ruby
258
+ tree.include? :x # => true
259
+ tree.include? [:x, :y] # => true
260
+ ```
261
+
262
+ `include?` can also check whether a tree structure (incl. a hash) is a sub tree of a `Sycamore::Tree`.
263
+
264
+ ```ruby
265
+ tree.include?(x: 1, y: 2) # => true
266
+ ```
267
+
268
+ `to_h` returns the tree as a Hash.
269
+
270
+ ```ruby
271
+ tree.to_h # => {:x=>1, :y=>{2=>"a"}}
272
+ ```
273
+
274
+ ### Accessing absent trees
275
+
276
+ There is another major difference in the access method behaviour of a Scyamore tree in comparison to hashes: The child access methods even return a tree when it does not exist. When you ask a hash for a non-existent element with the `[]` operator, you'll get a `nil`, which is an incarnation of the null-problem and the cause of many bug tracking sessions.
277
+
278
+ ```ruby
279
+ hash = {x: 1, y: {2 => "a"}}
280
+ hash[:z] # => nil
281
+ hash[:z][3] # => NoMethodError: undefined method `[]' for nil:NilClass
282
+ ```
283
+
284
+ Sycamore on the other side returns a special tree, the `Nothing` tree:
285
+
286
+ ```ruby
287
+ tree = Tree[x: 1, y: {2 => "a"}]
288
+ tree[:z] # => #<Sycamore::Nothing>
289
+ tree[:z][3] # => #<Sycamore::Nothing>
290
+ ```
291
+
292
+ `Sycamore::Nothing` is a singleton `Tree` implementing a [null object](https://en.wikipedia.org/wiki/Null_Object_pattern). It behaves on every query method call like an empty tree.
293
+
294
+ ```ruby
295
+ Sycamore::Nothing.empty? # => true
296
+ Sycamore::Nothing.size # => 0
297
+ Sycamore::Nothing[42] # => #<Sycamore::Nothing>
298
+ ```
299
+
300
+ Sycamore adheres to a strict [command-query-separation (CQS)](https://en.wikipedia.org/wiki/Command%E2%80%93query_separation). A method is either a command changing the state of the tree and returning `self` or a query method, which only computes and returns the results of the query, but leaves the state unchanged. The only exception to this strict separation is made, when it is necessary in order to preserve Hash compatibility. All query methods are supported by the `Sycamore::Nothing` tree with empty tree semantics.
301
+
302
+ Among the command methods are two subclasses: additive command methods, which add elements and destructive command methods, which remove elements. These are further refined into pure additive and pure destructive command methods, which either support additions or deletions only, not both operations at once. The `Sycamore::Tree` extends Ruby's reflection API with class methods to retrieve the respective methods: `query_methods`, `command_methods`, `additive_command_methods`, `destructive_command_methods`, `pure_additive_command_methods`, `pure_destructive_command_methods`.
303
+
304
+ ```ruby
305
+ Tree.command_methods
306
+ # => [:add, :<<, :replace, :create_child, :[]=, :delete, :>>, :clear, :compact, :replace, :[]=, :freeze]
307
+ Tree.additive_command_methods
308
+ # => [:add, :<<, :replace, :create_child, :[]=]
309
+ Tree.pure_additive_command_methods
310
+ # => [:add, :<<, :create_child]
311
+ Tree.pure_destructive_command_methods
312
+ # => [:delete, :>>, :clear, :compact]
313
+ ```
314
+
315
+ Pure destructive command methods on `Sycamore::Nothing` are no-ops. All other command methods raise an exception.
316
+
317
+ ```ruby
318
+ Sycamore::Nothing.clear # => #<Sycamore::Nothing>
319
+ Sycamore::Nothing[:foo] = :bar
320
+ # => Sycamore::NothingMutation: attempt to change the Nothing tree
321
+ ```
322
+
323
+ But inspecting the `Nothing` tree returned by `Tree#[]` further shows, that this isn't the end of the story.
324
+
325
+ ```ruby
326
+ tree[:z].inspect
327
+ # => absent child of node :z in #<Sycamore::Tree:0x3fc88e04a470 {:x=>1, :y=>{2=>"a"}}>
328
+ tree[:z][3].inspect
329
+ # => absent child of node 3 in absent child of node :z in #<Sycamore::Tree:0x3fc88e04a470 {:x=>1, :y=>{2=>"a"}}>
330
+ ```
331
+
332
+ We'll actually get an `Absence` object, a [proxy object](https://en.wikipedia.org/wiki/Proxy_pattern) for the requested not yet existing tree. As long as we don't try to change it, this `Absence` object delegates all method calls to `Sycamore::Nothing`. But as soon as we call a non-pure-destructive command method, the missing tree will be created, added to the parent tree and the method call gets delegated to the now existing tree.
333
+
334
+ ```ruby
335
+ tree[:z] = 3
336
+ tree.to_h # => {:x=>1, :y=>{2=>"a"}, :z=>3}
337
+ ```
338
+
339
+ So a `Sycamore::Tree` is a tree, on which the nodes grow automatically, but only when needed. And this works recursively on arbitrarily deep nested absent trees.
340
+
341
+ ```ruby
342
+ tree[:some][:very][:deep] = :node
343
+ tree.to_h # => {:x=>1, :y=>{2=>"a"}, :z=>3, :some=>{:very=>{:deep=>:node}}}
344
+ ```
345
+
346
+ In order to determine whether a node has no children, you can simply use `empty?`.
347
+
348
+ ```ruby
349
+ tree = Tree[a: 1]
350
+ tree[:a].empty? # => false
351
+ tree[:b].empty? # => true
352
+ ```
353
+
354
+ But how can you distinguish an empty from a missing tree?
355
+
356
+ ```ruby
357
+ user = Tree[name: 'Adam', shopping_cart_items: []]
358
+
359
+ user[:shopping_cart_items].empty? # => true
360
+ user[:foo].empty? # => true
361
+ ```
362
+
363
+ One way is the use of the `absent?` method, which only returns `true` on an `Absence` object.
364
+
365
+ ```ruby
366
+ user[:shopping_cart_items].absent? # => false
367
+ user[:foo].absent? # => true
368
+ ```
369
+
370
+ Another possibility, without the need to create the `Absence` in the first place is the `leaf?` method, since it also checks for the presence of a node.
371
+
372
+ ```ruby
373
+ user.leaf? :shopping_cart_items # => true
374
+ user.leaf? :foo # => false
375
+ ```
376
+
377
+ But the `leaf?` method has as similar problem in this respect: it doesn't differentiate between absent and empty children.
378
+
379
+ ```ruby
380
+ tree = Tree[foo: nil, bar: []]
381
+ tree.leaf? :foo # => true
382
+ tree.leaf? :bar # => true
383
+ ```
384
+
385
+ `strict_leaf?` and `strict_leaves?` (or their short aliases `sleaf?` and `sleaves?`) are more strict in this regard: when a node has an empty child tree it is considered a leaf, but not a strict leaf.
386
+
387
+ ```ruby
388
+ tree.strict_leaf? :foo # => true
389
+ tree.strict_leaf? :bar # => false
390
+ ```
391
+
392
+ Besides `absent?`, the congeneric methods `blank?` (as an alias of `empty?`) and its negation `present?` are ActiveSupport compatible available. Unfortunately, the natural expectation of `Tree#present?` and `Tree#absent?` to be mutually opposed leads astray.
393
+
394
+ ```ruby
395
+ user[:shopping_cart_items].absent? # => false
396
+ user[:shopping_cart_items].present? # => false
397
+ ```
398
+
399
+ The risks rising from an ActiveSupport incompatible `present?` is probably greater then this inconsistence. So, if you want check if a tree is not absent, use `existent?` as the negation of `absent?`.
400
+
401
+ Beside these options, `fetch` is also a method to handle this situation in a nuanced way.
402
+
403
+ ```ruby
404
+ user.fetch(:shopping_cart_items) # => #<Sycamore::Tree:0x3febb9c9b3d4 {}>
405
+ user.fetch(:foo)
406
+ # => KeyError: key not found: :foo
407
+ user.fetch(:foo, :default) # => :default
408
+ ```
409
+
410
+ Empty child trees also play a role when determining equality. The `eql?` and `==` equivalence differ exactly in their handling of this question: `==` treats empty child trees as absent trees, while `eql?` doesn't.
411
+
412
+ ```ruby
413
+ Tree[:foo].eql? Tree[foo: []] # => false
414
+ Tree[:foo] == Tree[foo: []] # => true
415
+ ```
416
+
417
+ All empty child trees can be removed with `compact`.
418
+
419
+ ```ruby
420
+ Tree[:foo].eql? Tree[foo: []].compact # => true
421
+ ```
422
+
423
+ An arbitrary structure can be compared with a `Sycamore::Tree` for equality with `===`.
424
+
425
+ ```ruby
426
+ Tree[:foo, :bar] === [:foo, :bar] # => true
427
+ Tree[:foo, :bar] === Set[:foo, :bar] # => true
428
+ Tree[:foo => :bar] === {:foo => :bar} # => true
429
+ ```
430
+
431
+
432
+ ### Changing trees
433
+
434
+ Let's examine the command methods to change the contents of a tree. The `add` method or the `<<` operator as its alias allows the addition of one, multiple or a tree structure of nodes.
435
+
436
+ ```ruby
437
+ tree = Tree.new
438
+ tree << 1
439
+ tree << [2, 3]
440
+ tree << {3 => :a, 4 => :b}
441
+ puts tree
442
+ > Tree[1=>nil, 2=>nil, 3=>:a, 4=>:b]
443
+ ```
444
+
445
+ The `[]=` operator is Hash-compatible supported.
446
+
447
+ ```ruby
448
+ tree[5] = :c
449
+ puts tree
450
+ > Tree[1=>nil, 2=>nil, 3=>:a, 4=>:b, 5=>:c]
451
+ ```
452
+
453
+ Note that this is just an `add` with a previous call of `clear`, which deletes all elements of the tree. This means, you can safely assign another tree without having to think about object identity.
454
+
455
+ If you want to explicitly state, that a node doesn't have any children, you can specify it in the following equivalent ways.
456
+
457
+ ```ruby
458
+ tree[:foo] = []
459
+ tree[:foo] = {}
460
+ ```
461
+
462
+ To remove a child tree entirely, you can assign `Nothing` or `nil` to the parent node.
463
+
464
+ ```ruby
465
+ tree[:foo] = Nothing
466
+ tree[:foo] = nil
467
+ ```
468
+
469
+ If you really want to overwrite the current child nodes with a single `nil` node, you have to do it in the following way.
470
+
471
+ ```ruby
472
+ tree[:foo] = [nil]
473
+ ```
474
+
475
+ Note that all of these values are interpreted consistently inside input tree structures on creation, addition, deletion etc., i.e. empty Enumerables become empty child trees, `Nothing` or `nil` are used as place holders for the explicit negation of a child and `[nil]` is used for a child trees with a single `nil` node.
476
+
477
+ ```ruby
478
+ puts Tree[ a: { b: nil }, c: { d: []}, d: [nil] ]
479
+ >Tree[:a=>:b, :c=>{:d=>[]}, :d=>[nil]]
480
+ ```
481
+
482
+ Beside the deletion of all elements with the already mentioned `clear` method, single or multiple nodes and entire tree structures can be removed with `delete` or the `>>` operator.
483
+
484
+ ```ruby
485
+ tree >> 1
486
+ tree >> [2, 3]
487
+ tree >> {4 => :b}
488
+ puts tree
489
+ > Tree[5=>:c, :foo=>[]]
490
+ ```
491
+
492
+ When removing a tree structure, only child trees with no more existing nodes get deleted.
493
+
494
+ ```ruby
495
+ tree = Tree[a: [1,2]]
496
+ tree >> {a: 1}
497
+ puts tree
498
+ > Tree[:a=>2]
499
+
500
+ tree = Tree[a: 1, b: 2]
501
+ tree >> {a: 1}
502
+ puts tree
503
+ > Tree[:b=>2]
504
+ ```
505
+
506
+
507
+ ### Iterating trees
508
+
509
+ The fundamental `each` and with that all Enumerable methods behave Hash-compatible.
510
+
511
+ ```ruby
512
+ tree = Tree[ 1 => {a: 'foo'}, 2 => :b, 3 => nil ]
513
+ tree.each { |node, child| puts "#{node} => #{child}" }
514
+
515
+ > 1 => Tree[:a=>"foo"]
516
+ > 2 => Tree[:b]
517
+ > 3 => Tree[]
518
+ ```
519
+
520
+ `each_path` iterates over all paths to leafs of a tree.
521
+
522
+ ```ruby
523
+ tree.each_path { |path| puts path }
524
+
525
+ > #<Path: /1/a/foo>
526
+ > #<Path: /2/b>
527
+ > #<Path: /3>
528
+ ```
529
+
530
+ The paths are represented by `Sycamore::Path` objects and are basically an Enumerable of the nodes on the path, specifically optimized for the enumeration of the set of paths of a tree. It does this, by sharing nodes between the different path objects. This means in the set of all paths, every node is contained exactly once, even the internal nodes being part of multiple paths.
531
+
532
+ ```ruby
533
+ Tree['some possibly very big data chunk' => [1, 2]].each_path.to_a
534
+ # => [#<Sycamore::Path["some possibly very big data chunk",1]>,
535
+ # #<Sycamore::Path["some possibly very big data chunk",2]>]
536
+ ```
537
+
538
+
539
+ ### Searching in trees
540
+
541
+ `search` returns the set of all paths to child trees containing a node or tree.
542
+
543
+ ```ruby
544
+ tree = Tree[ 1 => {a: 'foo'}, 2 => :b, 3 => [:a, :b, :c] ]
545
+ tree.search :a # => [#<Sycamore::Path[1]>, #<Sycamore::Path[1]>]
546
+ tree.search a: 'foo' # => [#<Sycamore::Path[1]>]
547
+ ```
548
+
549
+ If you search for multiple nodes, only the paths to child trees containing all of the given nodes are returned.
550
+
551
+ ```ruby
552
+ tree.search [:b, :c] # => [#<Sycamore::Path[3]>]
553
+ ```
554
+
555
+ All `Tree` methods for which it makes sense accept path objects as input instead or in combination with nodes or tree structures. This allows it to apply the search results to any of these methods.
556
+
557
+
558
+ ## Getting help
559
+
560
+ - [RDoc](http://www.rubydoc.info/gems/sycamore/)
561
+ - [Gitter](https://gitter.im/marcelotto/sycamore)
562
+
563
+
564
+ ## Contributing
565
+
566
+ see [CONTRIBUTING](CONTRIBUTING.md) for details.
567
+
568
+
569
+ ## License and Copyright
570
+
571
+ (c) 2015-2016 Marcel Otto. MIT Licensed, see [LICENSE](LICENSE.txt) for details.
data/Rakefile ADDED
@@ -0,0 +1,36 @@
1
+ require 'bundler/gem_tasks'
2
+
3
+ begin
4
+ require 'rspec/core/rake_task'
5
+ RSpec::Core::RakeTask.new(:spec)
6
+ rescue LoadError
7
+ puts "Couldn't find RSpec core Rake task"
8
+ end
9
+
10
+ begin
11
+ require 'yard'
12
+ YARD::Rake::YardocTask.new do |t|
13
+ t.options = ['--verbose']
14
+ t.files = ['lib/**/*.rb', 'doc/**/*.md']
15
+ t.stats_options = ['--list-undoc']
16
+ end
17
+ rescue LoadError
18
+ puts "Couldn't find YARD"
19
+ end
20
+
21
+ begin
22
+ require 'yard-doctest'
23
+ YARD::Doctest::RakeTask.new do |task|
24
+ task.doctest_opts = %w[]
25
+ task.pattern = 'lib/**/*.rb'
26
+ end
27
+ rescue LoadError
28
+ puts "Couldn't find yard-doctest"
29
+ end
30
+
31
+ task :default =>
32
+ if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby'
33
+ [:spec]
34
+ else
35
+ [:spec, 'yard:doctest']
36
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.4.1
data/bin/console ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'sycamore/extension'
5
+
6
+ require 'pry'
7
+ Pry.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
8
+