Class: Calyx::Grammar::Production::WeightedChoices

Inherits:
Object
  • Object
show all
Defined in:
lib/calyx.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection) ⇒ WeightedChoices

Returns a new instance of WeightedChoices.



130
131
132
# File 'lib/calyx.rb', line 130

def initialize(collection)
  @collection = collection
end

Class Method Details

.parse(productions, registry) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/calyx.rb', line 112

def self.parse(productions, registry)
  weights_sum = productions.reduce(0) do |memo, choice|
    memo += choice.last
  end

  raise 'Weights must sum to 1' if weights_sum != 1.0

  choices = productions.map do |choice, weight|
    if choice.is_a?(String)
      [Concat.parse(choice, registry), weight]
    elsif choice.is_a?(Symbol)
      [NonTerminal.new(choice, registry), weight]
    end
  end

  self.new(choices)
end

Instance Method Details

#evaluateObject



134
135
136
137
138
139
140
# File 'lib/calyx.rb', line 134

def evaluate
  choice = @collection.max_by do |_, weight|
    rand ** (1.0 / weight)
  end.first

  choice.evaluate
end