Class: Calyx::Grammar::Production::WeightedChoices
- Inherits:
-
Object
- Object
- Calyx::Grammar::Production::WeightedChoices
- Defined in:
- lib/calyx/grammar/production/weighted_choices.rb
Class Method Summary collapse
Instance Method Summary collapse
- #evaluate ⇒ Object
-
#initialize(collection) ⇒ WeightedChoices
constructor
A new instance of WeightedChoices.
Constructor Details
#initialize(collection) ⇒ WeightedChoices
23 24 25 |
# File 'lib/calyx/grammar/production/weighted_choices.rb', line 23 def initialize(collection) @collection = collection end |
Class Method Details
.parse(productions, registry) ⇒ Object
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/calyx/grammar/production/weighted_choices.rb', line 5 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
#evaluate ⇒ Object
27 28 29 30 31 32 33 |
# File 'lib/calyx/grammar/production/weighted_choices.rb', line 27 def evaluate choice = @collection.max_by do |_, weight| rand ** (1.0 / weight) end.first choice.evaluate end |