File: seasons.rb

package info (click to toggle)
ruby-parslet 1.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 908 kB
  • ctags: 473
  • sloc: ruby: 5,220; makefile: 2
file content (46 lines) | stat: -rw-r--r-- 956 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
$:.unshift File.dirname(__FILE__) + "/../lib"

require 'parslet'
require 'pp'

tree = {:bud => {:stem => []}}

class Spring < Parslet::Transform
  rule(:stem => sequence(:branches)) {
    {:stem => (branches + [{:branch => :leaf}])}
  }
end
class Summer < Parslet::Transform
  rule(:stem => subtree(:branches)) {
    new_branches = branches.map { |b| {:branch => [:leaf, :flower]} }
    {:stem => new_branches}
  }
end
class Fall < Parslet::Transform
  rule(:branch => sequence(:x)) {
    x.each { |e| puts "Fruit!" if e==:flower }
    x.each { |e| puts "Falling Leaves!" if e==:leaf }
    {:branch => []}
  }
end
class Winter < Parslet::Transform
  rule(:stem => subtree(:x)) {
    {:stem => []}
  }
end

def do_seasons(tree)
  [Spring, Summer, Fall, Winter].each do |season|
    p "And when #{season} comes"
    tree = season.new.apply(tree)
    pp tree
    puts
  end
  tree
end

# What marvel of life!
tree = do_seasons(tree)
tree = do_seasons(tree)